How can I deinitialize x inside the free_x function? I have to do it in order to fit to an API method. I can very easily deinitialize x just by assigning null to it but I have to do it inside the free_x function.
typedef struct
{
int field1;
void *field2;
}my_struct;
static my_struct var;
int main(void)
{
void *x;
alloc_x(&x);
free_x(x); // x = NULL works but not allowed
return 0;
}
void alloc_x(void **param)
{
*param = (my_struct *)&var;
}
void free_x(void *param)
{
// how can I free param here?
}
Simple answer: your code is already complete, so do no more.
Explanation: You do not allocate memory (on a heap or stack or elsewhere) so there is nothing to free. You do not take ownership of any resources that have to be returned, of set any flags that need to be cleared, or increment any semaphores that need to be decremented, etc.
You are implementing an API, but just because there is a function prototype that does not mean your implementation has to do anything, if it doesn't need to. Just change the comment to explain that there is nothing to do and leave the function empty.
void alloc_x(void **param)
{
*param = &var; // No need to cast here, just assign.
}
void free_x(void *param)
{
// Nothing allocated, taken, incremented, etc. in alloc_x, so ...
// nothing to free, release, decrement, etc. here in free_x.
}
The code that is using the API is expecting the memory behind the param
or x
pointer to have been freed after the call, so it shouldn't be doing anything with its variable afterwards anyway. It's not your problem if they do, but it will be your problem if you go diddling round with the caller's x
variable!