开发者

what's wrong with using malloc like this?

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 *开发者_C百科 (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 )).


char *msg = malloc(sizeof(MESSAGE_LENGTH));

Is probably not doing what you're thinking. I'm assuming MESSAGE_LENGTH is some #define, and if so, then it's likely you're getting the sizeof(int) or so, rather than allocating a block of MESSAGE_LENGTH bytes.


The size of something is not its value:

pax$ cat qq.c
    #include <stdio.h>
    #define MSGLEN 50
    int main (void) {
        printf ("sizeof(MSGLEN) = %d\n", sizeof(MSGLEN));
        printf ("       MSGLEN  = %d\n", MSGLEN);
        return 0;
    }

pax$ gcc -o qq qq.c

pax$ ./qq
sizeof(MSGLEN) = 4
       MSGLEN  = 50

If you want fifty bytes, use MSG_LEN, not its size. The code:

#define MESSAGE_LENGTH 50
char *msg = malloc(sizeof(MESSAGE_LENGTH));
memset(msg, 0, MESSAGE_LENGTH);

will allocate four bytes (assuming MESSAGE_LENGTH actually evaluates as an integer (on a system with four-byte integers (the standard doesn't mandate this))) but try to fill fifty bytes, not a good idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜