A
ashok.anbalan
I wrote a simple program to get a feel of the way free() works.
/*free/malloc usage.*/
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
// LOCATION_1
// int i =5;
int *ip= (int *) malloc (sizeof(int));
//LOCATION_2
int i = 5;
ip = &i;
printf ("Address of i is: %p \n", ip);
free(ip);
printf ("Address of i (after calling free) is: %p \n", ip);
ip = NULL;
printf ("Address of i (after assigning it to NULL) is: %p \n", ip);
return 0;
}
I use gcc on cygwin & here are two things that I observed:
1. If the statement "int i =5" at LOCATION_1 is uncommented & instead
the assignment at LOCATION_2 is commented, this program core dumps. I
am not sure why this happens.
2. Even after calling free(), the address printed is same as the one
before calling free. Hence, my understanding is that the free() call
suggests that memory be returned back to the system, although the
pointer variable ip will become unusable only where the scope of ip
logically ends. IS this understanding correct?
Can someone clarify these?
Thanks,
Ashok
/*free/malloc usage.*/
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
// LOCATION_1
// int i =5;
int *ip= (int *) malloc (sizeof(int));
//LOCATION_2
int i = 5;
ip = &i;
printf ("Address of i is: %p \n", ip);
free(ip);
printf ("Address of i (after calling free) is: %p \n", ip);
ip = NULL;
printf ("Address of i (after assigning it to NULL) is: %p \n", ip);
return 0;
}
I use gcc on cygwin & here are two things that I observed:
1. If the statement "int i =5" at LOCATION_1 is uncommented & instead
the assignment at LOCATION_2 is commented, this program core dumps. I
am not sure why this happens.
2. Even after calling free(), the address printed is same as the one
before calling free. Hence, my understanding is that the free() call
suggests that memory be returned back to the system, although the
pointer variable ip will become unusable only where the scope of ip
logically ends. IS this understanding correct?
Can someone clarify these?
Thanks,
Ashok