If an array of function pointers is statically allocated, do I still need to free()
it? Lets say I have this code:
typedef void (*test_ptr)(void);
int main(void)
{
test_ptr test[3];
test[0] = a;
test[1] = b;
test[2] = c;
}
So, when I would be done with it, would I have to free all the pointers, maybe like so:
for(int i = 0; i < 3; i++) {
free(test[i]);
}
Or is it automatically de-allocated when function ends, like other arrays?
Absolutely not!
An array allocated like that is located on the stack, and free
will fail horribly if you try it.
As an aside, the array you show is not "static". I think you mean "local", or even "auto" (although that can be confused with a C++ concept).
Aside no. 2: allocation on the stack means that you should not allocate large arrays this way. The stack typically has limited capacity, so anything large should be allocated via malloc
.
So, when I would be done with it, would I have to free all the pointers
No. You must not because free(ptr)
is used only when pointer ptr
is previously returned by any of malloc
family functions.
Passing free
a pointer to any other object (like a variable or array element) causes undefined behaviour .
[...] If
ptr
is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call tofree
orrealloc
, the behavior is undefined .
Or is it automatically de-allocated when function ends, like other arrays?
Yes. It will no longer exist once its enclosing function returns.
Automatic local variables like the ones in your case are destroyed as soon as the function in which they are created gets over. In your case, they will be destroyed when the main()
function gets over.
So you don't have to explicitly free()
those variables.
Does that code own the pointed-to-object, and was it allocated with one of the allocation-functions corresponding to free
( malloc
realloc
calloc
)?
If so, free
it at the end.
If not, desist.
You are clearly in the second case...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.