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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With