Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free array of function pointers

Tags:

arrays

c

pointers

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?

like image 307
user1806687 Avatar asked Oct 19 '25 06:10

user1806687


1 Answers

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.

C11: 7.22.3.3 The free function:

[...] 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 to free or realloc, 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.

like image 165
haccks Avatar answered Oct 20 '25 20:10

haccks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!