-4

Everybody knows that you have to free() pointers, when you use malloc() because the memory is allocated in the heap, which is not kept account of by the process.

But why don't I have to use free() when assigning a pointer without a heap:

char* text0 = calloc(20, sizeof (char));
strncpy(text0, "Hello World", 20);  // Remember to use `free()`!
char* text1 = "Goodbye World!"; // No need for `free()`?

Isn't text1 also a pointer on the stack pointing to the memory allocated on the heap? Why is there no need for free()?

hgiesel
  • 5,430
  • 2
  • 29
  • 56

2 Answers2

4

The string constant "Goodbye World!" is placed in a global, read-only section of memory at program startup. It is not allocated on the heap. Same goes for "Hello World".

So after the assignment, text1 points to this static string. Since the string does not exist on the heap, there's no need to call free.

dbush
  • 205,898
  • 23
  • 218
  • 273
3

free must be used for all memory allocated with malloc. You allocate memory from the heap and must return it so you can use it later again.

char* text0 = calloc(20, sizeof(char));    // this memory must be freed.

In:

text0 = "Hello World";

you ovewrite the pointer to the allocated memory. The memory is now lost and cannot be reclaimed/reused again.

Note the parenthesis around char in sizeof(char) and note that I dropped the * before text0 as you are assigning the address of the constant string to a variable of type "pointer to character". Turn warnings on when compiling!

You should have done:

free(text0);
text0 = "Hello World";  // DON'T use `free()`!

Note again I dropped the *. More reasons to turn warnings on when compiling.

char* text1 = "Goodbye World!"; // No need for `free()`?

No, no need to call free because you did not allocate from the heap.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
  • Your answer has some problems. `sizeof char` requires parens. `*text0 = "..."` is wrong as `*text0` is a `char`. – Spikatrix Apr 09 '16 at 12:51
  • @Cool-Guy, parenthesis around `sizeof char`: that is his code and later I tell him to turn warnings on. I'll add this to my answer. – Paul Ogilvie Apr 09 '16 at 14:02
  • Your answer is still confusing. You say that "_You should have done: `*text0 = "Hello World";`_" But that's wrong as `*text0` is a `char` and you're trying to assign a string literal to it which makes no sense. – Spikatrix Apr 09 '16 at 15:07
  • @Cool-guy, I fixed it. Unfortunately the text gets longer and doesn't focus on his thinking error as good anymore (a reason why I sometimes perfer to leave the minor errors in). – Paul Ogilvie Apr 09 '16 at 15:38