bharadwaj bharadwaj - 1 month ago 10
C Question

Free a pointer local to a function and return the pointer

I have a C code similar to this. How can I free the pointer and return it ? If I create another local pointer variable and assign

p
to that local pointer variable, it is showing a warning that local variable pointer cannot be returned. Note that I have a recursion so I want to free up the pointer in the function itself. Any workaround. Thanks in advance.

char * ABCfunction(){
char * p = malloc(10*sizeof(char));
//do something with p
ABCfunction();
return p;
//free(p); //Want to do both.
}


UPDATE: Yes, I know that it makes no sense and we cannot do both. I am asking for an alternative approach. The problem is if I don't free the pointer, it is consuming a lot of memory for high input values. I want to get rid of high memory usage.

Answer

Want to do both.

That is not a good goal.

If you free the pointer, you should not return the pointer. Otherwise, the calling function will get a dangling pointer.

Note that I have a recursion so I want to free up the pointer in the function itself.

Make sure you capture the returned pointer, use it, and then free it.

Here's what your function should look like:

char * ABCfunction()
{
   char * p = malloc(10*sizeof(char));
   //do something with p

   char* p1 = ABCfunction();
   // Use p1.
   // Then free p1
   free(p1);

   return p;
}