Originally Posted by
aravindsreeram
I'm trying to free a char pointer, and I see the below behaviour
Case 1:
Code:
int main()
{
char *oneLineTerm;
free(oneLineTerm);
printf("freed memory"); /* Not printed */
}
Case 2:
Code:
int main()
{
char *oneLineTerm;
if(*oneLineTerm != NULL)
free(oneLineTerm);
printf("freed memory"); /* Printed */
}
What exactly happening in free() function here?
free() is ONLY used if memory has been allocated using malloc(), calloc(), or realloc()! Or some other function that returns a pointer to memory it allocated. Always read the man pages for functions to understand the function completely!
From "man 3 free" on my Linux system:
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc(), or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.
Please study my version of your code for a proper use of free():
Code:
#include <stdio.h>
#include <stdlib.h>
#define DIM 100
int main()
{
char *oneLineTerm = NULL; // ALL local variables MUST be initialized
oneLineTerm = malloc(DIM);
if(oneLineTerm == NULL) // Unknown error allocating the memory
{
printf("ERROR: Memory not allocated, Nothing to see here, move along, move along!\n");
return EXIT_FAILURE;
}
// Memory has been allocated
// More code here using the pointer
free(oneLineTerm); // NOW, free the allocated memory
oneLineTerm = NULL; // NULL the pointer in case some other code is inserted below before exiting!
printf("freed memory\n");
return 0;
}