0

As I was reading, there is a need to use free(), BUT what happen next? I mean if I got something like that:

char word[] = "abc";
char *copy;
copy = (char*) malloc(sizeof(char) * (strlen(word) + 1));
strcpy(copy, word);
free(copy);
printf("%s", copy);

It is going to write me "abc". Why?

Kubekk
  • 133
  • 1
  • 8
  • 6
    Accessing freed memory triggers *undefined behavior*. There's no "why". Anything can happen. (And stop casting the result of `malloc`). – AnT stands with Russia Nov 21 '16 at 18:55
  • Possible duplicate of [malloc / free. can read from freed memory](http://stackoverflow.com/questions/9673733/malloc-free-can-read-from-freed-memory) – Random Davis Nov 21 '16 at 19:16

4 Answers4

4

After using free(), your pointer copy still points to the same memory location. free() does not actually delete what is written there in memory but rather tells the memory management that you do not need that part of memory anymore. That is why it still outputs abc. However, your OS could have reassigned that memory to another application or some new thing you allocate in your application. If you are unlucky, you will get an segmentation fault.

clocktown
  • 371
  • 1
  • 3
  • 10
  • 4
    I'd perhaps rephrase that to "If you are LUCKY, you will get a segmentation fault" – schil227 Nov 21 '16 at 19:02
  • You're right, of course. If you are unlucky you are overwriting used memory without any warning or Error whatsoever, wondering about obscure Bugs. – clocktown Dec 04 '16 at 11:49
2

free() deallocates the memory previously allocated by a calloc, malloc, or realloc. You should not access memory that has been free'd, as the behaviour is not defined. It's only a coincidence, that it still holds it's previous content.

It is a good idea to use tools as valgrind, which can tell you (among other things) whether or not you are trying to access deallocated memory. In linux terminal, you can do it like this:

valgrind ./yourProgram

Honza Dejdar
  • 947
  • 7
  • 19
0

Here is it explayned quite well:

C Reference -- free()

deallocating memory does not mean there is no Data anymore.

The Memory is just free for new allocations.

Accessing it will result in undefined behavior.

Dropye
  • 214
  • 3
  • 18
0

As others have said, the behavior is undefined when the code references a freed pointer. In this case you are reading it. However, writing to it would most likely be not allowed, and you should see a segmentation fault.

I recommend that you run it with the MALLOCDEBUG (e.g. on AIX it would be MALLOCDEBUG=validate_ptrs) or a similar environment variable on your platform, so that you will catch this error. However turning on MALLOCDEBUG can have a serious performance impact on your program. An alternative is to write your own free routine that also sets the freed pointer to NULL explicitly as shown below:

#define MYFREE(x) do { free((x)); (x) = NULL; } while(0);