Why does free() only set the 8 first bytes to zero

2019-06-04 21:45发布

问题:

I've a question about free() behavior.

Juste a simple code which use malloc and strcpy a char*. So, all is set on the HEAP :

(gdb) x/100b 0x602010
0x602010:   66  111 110 106 111 117 114 32
0x602018:   116 111 117 116 32  108 101 32
0x602020:   109 111 110 100 101 0   0   0
0x602028:   0   0   0   0   0   0   0   0
0x602030:   0   0   0   0   0   0   0   0
0x602038:   33  0   0   0   0   0   0   0

When I free the chunk with free(), the result is :

(gdb) x/100b 0x602010
0x602010:   0   0   0   0   0   0   0   0
0x602018:   116 111 117 116 32  108 101 32
0x602020:   109 111 110 100 101 0   0   0
0x602028:   0   0   0   0   0   0   0   0
0x602030:   0   0   0   0   0   0   0   0
0x602038:   33  0   0   0   0   0   0   0

Simple code to prove that :

int main ()
{
    const char * str = "Bonjour tout le monde";

    char *ptr = (char *) malloc (strlen(str) + 1);
    strcpy(ptr, str);

    printf("*ptr : %s\n\n", ptr);

    free(ptr);

    printf ("After free ptr = %p\n", ptr);
    printf ("Content ptr    : %s\n", ptr);
    printf ("Content ptr+8 : %s\n", ptr+8);

    return 0;
}

Output :

*ptr : Bonjour tout le monde

After free ptr = 0x13c7010
Content ptr    : 
Content ptr+8 : tout le monde

Does someone has the answer?

回答1:

free() is not required to clear memory, and really it shouldn't because doing so would take time and overwrite cached data for no universally required benefit.

It's certainly allowed to use the internal space for its own purposes. What you are seeing may be just a side effect of the allocator keeping track of free memory.



回答2:

A better question would be; why do you think it should do anything else? Where did you find documentation regarding the mandated implementation of free? It doesn't exist, so it makes no sense to ask such a question.

free simply has to mark that memory as freed. What happens to that block of memory after calling free is unspecified.


As an aside, this is UB:

printf ("Content ptr    : %s\n", ptr);
printf ("Content ptr+8 : %s\n", ptr+8);