Search code examples
cmallocheap-memoryfree

dynamiclly allocate and free in C


void* heap = malloc(100);
char *c = heap;
strcpy(c, "Terence");
printf("heap = %s\n", heap);
free(heap);
heap = malloc(100);
printf("heap = %s\n", heap);

the output is:

heap = Terence
heap = 

That is what I expect, but now I have a far more complex code, the structure is similar to the above, but the output is like:

heap = "Terence"
heap = "  ren  "

something like that.

It seems heap has not been cleaned up?

Is there a way to solve it?


Solution

  • The region of memory allocated by malloc has an indeterminate initial value.

    From the C Standard (emphasis mine):

    (c99, 7.20.3.3p2) "The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate*."

    Use calloc or memset after malloc to have a determinate value.