1
votes

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?

2
In a typical heap implementation, the free() function adds the block back to a list of free blocks. So odds are that you are seeing the side-effects of that operation, with the zeros written to indicate there is no previous and next pointer yet to other free blocks. Look in your CRT source code. - Hans Passant
And there are plenty of times that you might see other effects in just-freed memory. For example if using a debug runtime, most of the memory block will quite possibly be filled with some value that is more likely to crash your program if you mistakenly use it - and that value won't be zero. Basically, once you free the block it's not yours. What the runtime does with it is up to the runtime. - Michael Burr

2 Answers

6
votes

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.

4
votes

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);