iwander
iwander

Reputation: 81

free() replaces string with zero?

I could use a little help with free().

When I run the following:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, const char *argv[])
{
    char *mystring = malloc(6 * sizeof(char));
    strcpy(mystring, "Hello");
    printf("%p\n", mystring);
    printf("%s\n", mystring);
    free(mystring);
    printf("%p\n", mystring);
    printf("%d\n", *mystring);

    return 0;
}

I get:

0x8f46008
Hello
0x8f46008
0

Did free() replace the string 'Hello' from memory with zero?

Note: This is just for academic purposes. I would never reference freed memory for real.

Thanks, Frank

Upvotes: 1

Views: 111

Answers (3)

Borealid
Borealid

Reputation: 98509

The contents of mystring (*mystring, mystring[0], and friends) are undefined after you free the memory. You can not rely on it containing "Hello". You also cannot rely on it containing an ASCII NUL (as you see here).

You also cannot rely on reading it not causing a segmentation fault. Don't do it.

If you were to run this program in a memory checker like valgrind, you would see an error here about access to freed memory.

Upvotes: 2

templatetypedef
templatetypedef

Reputation: 372982

Once you have freed a block of memory, reading that memory again results in undefined behavior and is a serious security and stability hazard. You cannot count on anything holding true for memory that has been freed, so there is no guarantee whether the memory will be zeroed or not. Unless you are absolutely sure of what you're doing, don't reference memory after you've freed it.

As an amusing anecdote about this, the original SimCity game had a bug in it where it referenced memory that had been freed. In DOS, this ended up not causing a crash, but when it was ported to Windows the game started crashing repeatedly. The Windows team had to specifically build in a case into the OS such that if SimCity was run, a custom memory manager would be used to prevent this sort of crash. You can read the full story here.

In short, once it's freed, don't touch it. Otherwise you risk bugs that some poor programmer years down the line will have to fix for you. Tools like valgrind exist to detect these sorts of errors specifically because they're so nasty.

Hope this helps!

Upvotes: 6

Blindy
Blindy

Reputation: 67417

Maybe in debug mode on your specific computer and compiled with your specific compiler, in general though you should expect that piece of code to crash (or worse).

Upvotes: 0

Related Questions