Let's say we want to free the total memory used by a linked list in a program, I generally do it like this
typedef struct linked_list
{
int some_data;
struct linked_list *link;
}NODE;
int free_memory(NODE * head)
{
NODE * temp = NULL;
if(head == NULL)
return 0; // FAILURE IN FREEING MEMORY
else
{
while(head != NULL)
{
temp = head;
head = head -> link;
free(temp);
}
}
return 1; // SUCCESS IN FREEING MEMORY
}
Now suppose I've created an array
int * create_array(int size_of_array)
{
int * array = (int *)calloc(size_of_array,sizeof(int));
return array;
}
Rarely have I seen books freeing memory but sometimes I've seen this
# define SIZE 5
int * create_array( int );
int main()
{
int * my_array = create_array(SIZE);
// SOME OPERATION HAS BEEN DONE ON THE ARRAY
// NOW FREEING MEMORY
free(my_array);
return 0;
}
But I free memory like this
# define SIZE 5
int * create_array( int );
int main()
{
int * my_array = create_array(SIZE);
// SOME OPERATION HAS BEEN DONE ON THE ARRAY
// NOW FREEING MEMORY
free_memory(my_array, SIZE);
return 0;
}
int free_memory (int * array, int size_of_array)
{
if(array == NULL)
return 0;
else
{
int i;
for(i = size_of_array - 1; i >= 0; i--)
{
free(array[i]);
}
}
return 1;
}
So in a nut-shell, when we are freeing a linked list, we are freeing each node separately, but when we are freeing an array, the books are freeing only the first address.
Why this disparity?
(I'm sorry if this is a n00b question :P but i need to know)