Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to free char array of fixed length? [duplicate]

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?

like image 912
Sebastian S Avatar asked Apr 18 '15 13:04

Sebastian S


2 Answers

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.

like image 102
Iharob Al Asimi Avatar answered Sep 28 '22 00:09

Iharob Al Asimi


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.

like image 41
mattm Avatar answered Sep 28 '22 01:09

mattm