-
Free the pointer
Hello,
I need to write a function such that it frees all the pointers that I allocate.My code looks like this:
Code:
int someFunction()
{
//Allocating pointers.
szTemp1 = calloc(10, sizeof(char));
stTemp2 = calloc(10 , sizeof(char));
stTemp3 = calloc (10 , sizeof(char));
//Logic goes here
if ( something bad happened)
{
//free all pointers
free(szTemp1 );
free(szTemp2 );
free(szTemp3 );
return FAIL;
}
if( something else goes wrong)
{
//free all pointers
free(szTemp1 );
free(szTemp2 );
free(szTemp3 );
return FAIL;
}
//Finally in the end:
//free all pointers
free(szTemp1 );
free(szTemp2 );
free(szTemp3 );
return SUCCESS;
}
Here , instead of repeating the same lines to free the pointers everytime in the code, I would like to call a function which releases all pointers. How would i do it? I would not want to use the goto statement to achieve the same.
Please help.
-
I think it should be possible to write a function that accepts pointers as arguments and frees them. Something like:
Code:
void freeMultiplePointers(char *p1, char *p2, char *p3)
{
free(p1);
free(p2);
free(p3);
}
To make this function compatible with multiple types you can use void *p1, etc as arguments. I am not totally sure about this solution though.
-
So long as all the arguments are allocated by malloc/calloc, then it doesn't matter what type you pass to the function because free accepts void*, so yes, it's possible to use void* in the parameter list.