I got segmentation fault for the following code, could someone help me understand why?
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
The second time, I removed free(id); call from above, and kept the rest, I got the following error once the last malloc is called:
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
and finally, everything worked after I changed the first two lines in the function to:
char id[50];
char msg[MESSAGE_LENGTH];
Why is this? what could cause the assertion fail? Thank you.
If MESSAGE_LENGTH is an integer, then sizeof( MESSAGE_LENGTH ) is very different from MESSAGE_LENGTH. (It is likely 4 or 8.) You want malloc( MESSAGE_LENGTH ), not malloc( sizeof( MESSAGE_LENGTH )).