I am a little late in the discussion but here is my understanding.
Once you use malloc(), you create a memory block that you must manage... or free. So when to use free()?
Within a function, you want to free() any memory that you will not use outside of the function. This will prevent memory leaks.
If you want to access the memory outside the function, you have to return a pointer to the memory, since you cannot return memory from a function.
BTW, I'm still learning, so I could be wrong?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *tmp ()
{
char *output = malloc (8 * sizeof (char));
strcpy (output, "abcdefg");
printf ("In tmp(), char *output.\tAddress: %p\tContains: %s\n", output, output);
/* free(output); Using free here, would basically be saying: I no longer need the memory which contains "abcdefg". */
return output;
}
int main ()
{
char *string = tmp (); /* The pointer *string will point to the memory created with malloc() inside the tmp() function. */
printf ("In main(), char *string.\tAddress: %p\tContains: %s\n", string, string); /* Access the memory here. */
free (string); /* free() here since we are done with string. free() will free memory that was created with malloc() inside the tmp() function. */
return 0;
}