C Programming - Memory Allocation - Discussion
Discussion Forum : Memory Allocation - Find Output of Program (Q.No. 1)
1.
What will be the output of the program?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
p = (int *)malloc(20); /* Assume p has address of 1314 */
free(p);
printf("%u", p);
return 0;
}
Discussion:
57 comments Page 1 of 6.
Raj said:
6 years ago
The correct answer should be garbage value. Once memory free the value will be garbage value.
(3)
Hossam Ahmed said:
2 years ago
@All.
Here is my explanation.
Simply:
free() removes the data stored in the location but the pointer can still point at the same location.
When trying to access it again with the pointer, it gives a Garbage value.
So, the location is free as data storing not freeing or removing or making the pointer stop pointing at the location.
Here is my explanation.
Simply:
free() removes the data stored in the location but the pointer can still point at the same location.
When trying to access it again with the pointer, it gives a Garbage value.
So, the location is free as data storing not freeing or removing or making the pointer stop pointing at the location.
(2)
Akash Musale said:
7 years ago
The answer is garbage value.
(1)
Prasad said:
1 decade ago
Eventhough the array is deleted the pointer still pointing to memory location in heap area so we must assign null value to dangling pointer.
Manisha said:
1 decade ago
The 'free' does not delete the pointer. The dangling pointer remains.
Shreyans said:
1 decade ago
Using free() one time leads to Memory leak, i.e., in this case (hence the pointer still pointing to 1314 location that is became DanglingPointer).
Whereas using free() twice leads to memory/program crash.
Whereas using free() twice leads to memory/program crash.
AMEERUL said:
1 decade ago
Here p become dangling pointer it will totally depends on OS if after freeing memory region os allocate this region to another variable or function then it will give a random or garbage address. Otherwise 1314.
Abhijit said:
1 decade ago
I'm still confused.
Why its taking value 1314 only why not 1316 ?
Why its taking value 1314 only why not 1316 ?
Anshika said:
1 decade ago
Actually first it allocates 80 bytes to p. And then it free the memory of p. That means only allocated memory to it has been destroyed not its base address which is still 1314. So on printing the address of p it gives 1314 instead of giving garbage value.
Akarsh bajpai said:
1 decade ago
@Arnab Bhattacharya.
It is actual base address of the pointer allocated during runtime in memory ;here we are assuming it is 1314.
It is actual base address of the pointer allocated during runtime in memory ;here we are assuming it is 1314.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers