解决valgrind

时间:2017-10-27 00:40:24

标签: c memory-management struct valgrind

我很擅长使用valgrind并在C中编程。我试图理解以下valgrind消息

==6225== Invalid write of size 4
==6225==    at 0x10000144D: handle_client (server.c:82)
==6225==    by 0x10000186A: main (server.c:201)
==6225==  Address 0x100a83248 is 0 bytes after a block of size 8 alloc'd
==6225==    at 0x10000BE81: malloc (vg_replace_malloc.c:302)
==6225==    by 0x100001431: handle_client (server.c:80)
==6225==    by 0x10000186A: main (server.c:201)
==6225== 
==6225== Invalid write of size 4
==6225==    at 0x100001458: handle_client (server.c:83)
==6225==    by 0x10000186A: main (server.c:201)
==6225==  Address 0x100a8324c is 4 bytes after a block of size 8 alloc'd
==6225==    at 0x10000BE81: malloc (vg_replace_malloc.c:302)
==6225==    by 0x100001431: handle_client (server.c:80)
==6225==    by 0x10000186A: main (server.c:201)

它解析为代码,我试图分配一个结构(ClientContext)

#define DEFAULT_CC_CHANDLES 4
... 
[78]    // create the client context here
[79]    ClientContext* client_context = NULL;
[80]    client_context = malloc( sizeof(client_context) );
[81]    client_context->chandle_table = malloc( sizeof(GeneralizedColumnHandle) * DEFAULT_CC_CHANDLES );
[82]    client_context->chandles_in_use = 0;
[83]    client_context->chandle_slots = DEFAULT_CC_CHANDLES;

并且该结构的定义是:

typedef struct ClientContext {
    GeneralizedColumnHandle* chandle_table;
    int chandles_in_use;
    int chandle_slots;
    int client_fd;
} ClientContext;

那么究竟是什么造成了无效写入?我没有为结构分配足够的空间吗?我应该检查alloc是否首先返回有效指针吗?

3 个答案:

答案 0 :(得分:2)

您正在将指针的大小传递给malloc(),这还不够,请尝试

client_context = malloc(sizeof *client_context);

您的代码无效的原因是因为sizeof client_context等于sizeof(void *),这与sizeof(ClientContext)不同。

另外,请务必检查malloc()是否确实成功。

答案 1 :(得分:1)

client_context = malloc(sizeof(*client_context));

事实是你要将client_context分配给指针本身的大小而不是内部需要的大小。就像你char *一样:

char *str = malloc(sizeof(char) * ..);

您将char置于char *内,与结构

相同

答案 2 :(得分:0)

谢谢大家。通过更改

修复
client_context = malloc( sizeof(client_context) );

client_context = malloc( sizeof(ClientContext) );

我错误地将内存分配给变量client_context的大小而不是实际的struct ClientContext。