der*_*dji 0 c malloc assertions segmentation-fault
以下代码我有分段错误,有人可以帮我理解原因吗?
typedef struct ClientData {
int _clientId;
char _msg[200];
} ClientData_t;
// in a function
char *id = malloc(50);
char *msg = malloc(sizeof(MESSAGE_LENGTH));
memset(id, 0, 50);
memset(msg, 0, MESSAGE_LENGTH);
strcpy(id, &(buffer[1]));
strcpy(msg, &(buffer[50]));
free(id);
printf("this message can be printed\n");
ClientData_t *newData = malloc(sizeof(ClientData_t));
// I got segmentation fault for this malloc here
Run Code Online (Sandbox Code Playgroud)
第二次,我free(id);从上面删除了调用,并保留了其余的,一旦调用了最后一个malloc,我得到了以下错误:
mainClient1: malloc.c:3074: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
Abort
Run Code Online (Sandbox Code Playgroud)
最后,在我将函数中的前两行更改为:
char id[50];
char msg[MESSAGE_LENGTH];
Run Code Online (Sandbox Code Playgroud)
为什么是这样?什么可能导致断言失败?谢谢.
如果MESSAGE_LENGTH是整数,则sizeof(MESSAGE_LENGTH)与MESSAGE_LENGTH非常不同.(很可能是4或8.)你想要malloc(MESSAGE_LENGTH),而不是malloc(sizeof(MESSAGE_LENGTH)).