1

Suppose I have the following program

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

char *returnSomething()
{
    char *myString;
    myString = malloc(sizeof(char) * 50);

    strcpy(myString,"hello");

    free(myString);
    return myString;
}

int main(int argc, char const *argv[])
{

    char *myString = returnSomething();
    printf("%s",myString);

    return 0;
}

Why is it that this will successfully print "hello" when I free'd it before returning? I thought it woudn't print anything since I free'd the memory then returned the string afterwards. I assumed I always had to free it in main after printing it.

Is this just my mac compiler being nice?

FreeStyle4
  • 272
  • 6
  • 17
  • 5
    No, it's just that `free` doesn't necessarily erase memory or dump it into an erupting volcano, it just makes it available for future allocation. 'Use after free' though is a serious error, even though in short examples and particular implementations it doesn't trigger an instant meltdown of your program. – pvg Sep 14 '17 at 01:16
  • 2
    Once you free a pointer, *it's not yours* anymore. You're not allowed to use it. It's like a hotel room that you've checked out of--if you go back and take a nap there, maybe you'll surprize the maid, maybe you'll get arrested, or maybe nothing at all will happen. But nonetheless, *it doesn't belong to you*, and you're not supposed to use it. – Lee Daniel Crocker Sep 14 '17 at 01:26

2 Answers2

3

When you call free(myString), the memory myString points to is being freed, but the value of myString stays untouched, making the myString a dangling pointer. Accessing the memory that has already been freed can produces undefined behavior.

Using pointer after free()

  • 1
    **will** produce undefined behaviour. Even if there's no actual problem occurring because of it, it's still undefined. – paxdiablo Sep 14 '17 at 02:02
  • De-referencing the pointer is not needed to make it UB. Attempting to read `myString` (this pointer itself) after `free(myString)` before it is re-assigned is UB. – chux - Reinstate Monica Sep 14 '17 at 02:34
0

Why is it that this will successfully print "hello" when I free'd it before returning?

Code broke the rules.

Attempting to use the prior value in myString after free(myString) is undefined behavior (UB). @Lee Daniel Crocker

One possible UB is that data will still be there at a later time.

I thought it woudn't print anything

That would be defined behavior but this is UB. It is possible that nothing would print, code would error out, spin in a loop forever, or ....

It is UB.


Using pointer after free() is a good question/answer. Moving this to wiki

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256