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 6 of 6.
Vijay said:
8 years ago
Please explain the program.
Hrishikesh Dabir said:
8 years ago
@ALL.
The answer is A. Because in this case the address allocated is 1314. But when you actually compile it some address say 123456 is allocated for the first time.
Now. When you free, the memory allocated is freed but the pointer is still not null. So it still has the address 123456. And when you print it it will print 123456.
Now when you compile it for the second time. Some other addresses say 98765 is allowed. And all the same steps again. So yep, It is not random address.
The answer is A. Because in this case the address allocated is 1314. But when you actually compile it some address say 123456 is allocated for the first time.
Now. When you free, the memory allocated is freed but the pointer is still not null. So it still has the address 123456. And when you print it it will print 123456.
Now when you compile it for the second time. Some other addresses say 98765 is allowed. And all the same steps again. So yep, It is not random address.
Akash Musale said:
7 years ago
The answer is garbage value.
(1)
Raj said:
6 years ago
The correct answer should be garbage value. Once memory free the value will be garbage value.
(3)
Vss said:
3 years ago
The operator free() only frees the memory address from the pointer variable and returns the address to the operating system for re-use, but the pointer variable (p in this case) still points to the same old address.
FYI, free() is not an operator, it's a function.
FYI, free() is not an operator, it's a function.
Sarath said:
2 years ago
@All.
Here;
printf("%u",p) will give an error.
i.e change to printf("%p",p).
Here;
printf("%u",p) will give an error.
i.e change to printf("%p",p).
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)
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers