这样使用malloc有什么问题?
|
我在以下代码中遇到了细分错误,有人可以帮我理解为什么吗?
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
第二次,我从上面删除了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
最后,当我将函数的前两行更改为:
char id[50];
char msg[MESSAGE_LENGTH];
为什么是这样?什么会导致断言失败?谢谢。
没有找到相关结果
已邀请:
3 个回复
弛保矮瘦敖
茂坦湿床够
可能不是您在想什么。我假设
是一些
,如果是,那么您很可能会得到
左右,而不是分配
字节的块。
碧肮械淌设
如果要五十个字节,请使用
,而不是其大小。代码:
会分配四个字节(假设ѭ5实际上是一个整数(在具有四个字节整数的系统上(标准对此没有要求))),但尝试填充五十个字节,不是一个好主意。