Ç - 不能在客户端 - 服务器解决方案大小1的读出无效

问题描述 投票:0回答:2

客户端和服务器交换消息通过发送这种类型的结构:

typedef struct {
    op_t     op;   
    char sender[MAX_NAME_LENGTH+1];
} message_hdr_t;

typedef struct {
    char receiver[MAX_NAME_LENGTH+1];
    unsigned int   len;  
} message_data_hdr_t;

typedef struct {
    message_data_hdr_t  hdr;
    char               *buf;
} message_data_t;

typedef struct {
    message_hdr_t  hdr;
    message_data_t data;
} message_t;

消息客户端和服务器之间交换的到达正确和执行前进但Valgrind的返回错误:

==4179== Invalid read of size 1
==4179==    at 0x4C32D04: strlen (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4179==    by 0x50B84D2: vfprintf (vfprintf.c:1643)
==4179==    by 0x50BFF25: printf (printf.c:33)
==4179==    by 0x10A122: threadF (main.c:151)
==4179==    by 0x4E436DA: start_thread (pthread_create.c:463)
==4179==    by 0x517C88E: clone (clone.S:95)
==4179==  Address 0x5452134 is 0 bytes after a block of size 4 alloc'd
==4179==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4179==    by 0x109B2B: readData (connections.h:103)
==4179==    by 0x109C17: readMsg (connections.h:134)
==4179==    by 0x10A0B0: threadF (main.c:146)
==4179==    by 0x4E436DA: start_thread (pthread_create.c:463)
==4179==    by 0x517C88E: clone (clone.S:95)

我这是怎么填的结构在READDATA服务器();因为阅读可以考虑readn。

#define SYSCALL(r,c,msg) \
    if((r=c)==-1) {perror(msg);

//other reads and writes
msg->data.buf=malloc(msg->data.hdr.len*sizeof(char));
SYSCALL(notused,readn(fd,msg->data.buf,msg->data.hdr.len*sizeof(char)),"read_data_buf");            
if(notused==0){
    return -1;
}

而我得到错误,当我做的printf上的main.c:151

printf("BODY: %s\n",msg->data.buf);
c server client valgrind
2个回答
1
投票

大概

msg->data.buf=malloc(msg->data.hdr.len*sizeof(char));
SYSCALL(notused,readn(fd,msg->data.buf,msg->data.hdr.len*sizeof(char)),"read_data_buf");            

一定是

msg->data.buf=malloc(msg->data.hdr.len + 1);
SYSCALL(notused,readn(fd,msg->data.buf,msg->data.hdr.len),"read_data_buf");            
msg->data.buf[msg->data.hdr.len] = 0;

增加地方结束空字符,并将其设置

但是你肯定msg->data.buf是打印字符串?你如何在信息交换过程中编码您的结构?


sizeof(char)再次是1根据定义,它是无用的由它来乘以


1
投票

根据此消息

==4179==  Address 0x5452134 is 0 bytes after a block of size 4 alloc'd

你分配4个字节。

您的通话printf

printf("BODY: %s\n",msg->data.buf);

希望找到\0结束的字符串

也许你SYSCALL(notused,readn(...读取的字节中不包含这4个字节内'\0',所以strlen读取分配内存结束后的下一个字节。

解决办法之一是分配一个字节以上,并追加'\0'接收到的数据。

© www.soinside.com 2019 - 2024. All rights reserved.