I have been scratching my head regarding the memory 'behavior' with arrays decayed as pointers.
I have a function where an array of structures is created in a function (without explicit memory allocation) and then passed to another function as a pointer. Said function store the pointer in a static variable.
Reading this kind of code, I would say the pointer should be invalidated at the end of the first function (since no malloc was done) yet it is not. However, calling a free() on this pointer throws a glibc error : invalid pointer. Makes sense, since no malloc was called.
- Is there some implicit memory allocation being performed because of the decaying array ?
- Is there a way to properly free the memory after this ? I know the trivial answer would be to allocate the memory myself, I am mainly asking out of curiosity.
Edit : some dummy code as requested :
static structure* s_array = NULL;
void foo()
{
structure array[5];
bar(array); // array decaying as a pointer
}
void bar(structure* ptr)
{
s_array = array; // pointer stored in the static, not invalidated at the end of foo()
}
void freeBar()
{
free(s_array); // invalid pointer
}