9

As far as I can tell from the answers to other SO questions, I don't need to free fixed-length arrays like the following:

unsigned char buffer[16];

But in general one has to free memory whenever calling malloc, memcpy, etc.

My Question is: Do I need to call free in the following scenario:

unsigned char buffer[16];
memcpy(buffer, source, 16);
...
free(buffer); // needed?

To be more precise: Is the decision, whether heap or stack is used, based on the declaration or initialization of a variable?

Sebastian S
  • 4,420
  • 4
  • 34
  • 63
  • 5
    no, you **must not** free such an array. There's a reason non-static local variables are said to have *automatic* storage duration… Also, forget about "the stack" and "the heap". The C standard only specifies abstract semantics for automatic, static and dynamic storage duration. There's no requirement that they be implemented using stacks and heaps. – The Paramagnetic Croissant Apr 18 '15 at 13:26
  • 2
    where do you find that 'one has to free memory' for `memcpy` ? – tivn Apr 18 '15 at 13:30
  • @tivn In fact I was mistaken here. Updated question, so others won't learn wrong stuff ;) – Sebastian S Apr 18 '15 at 13:35
  • Essentially, you are answering your own question: Does `buffer` come from `malloc`, `calloc` or `realloc`? No. So you not only don't have to free it, but you may not free it. – glglgl Aug 04 '15 at 07:10

3 Answers3

21

You only free() pointers returned by malloc()/calloc()/realloc(), passing any pointer that was not returned by one of these functions is undefined behavior.

In the case where you allocate an array like

unsigned char buffer[16];

inside a function, the array will be automatically deallocated when it gets out of scope, i.e. when the function returns.

The array is in fact, only valid within the scope where it was declared so

if (condition != 0)
 {
    unsigned char buffer[16];
 }
/* here it was already deallocated */

the example above is a good one that justifies enabling -Wshadow with gcc.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
6

If an array is on the stack, you do not need to free it; it will automatically be reclaimed when the stack frame is popped.

If an array is on the heap (allocated using malloc or similar function), you need to free explictly. Otherwise you have a memory leak.

mattm
  • 5,851
  • 11
  • 47
  • 77
1

No, you have allocated your object on the stack, so no free is required. If you use malloc you will allocate the memory on the heap and then you have to free it.

Michael Aigner
  • 4,820
  • 4
  • 21
  • 33