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 2 of 6.
Ch .suresh royal said:
9 years ago
Explanation:
free(p); -------> Means deallocating memory pointed by the address 1314, but its address still present (1314) NOTE: REFERS TO DANGLING POINTER;
I) in printf, pritting the address so it will print (1314).
free(p); -------> Means deallocating memory pointed by the address 1314, but its address still present (1314) NOTE: REFERS TO DANGLING POINTER;
I) in printf, pritting the address so it will print (1314).
Muzammil said:
9 years ago
The free is a function which will free the data allocated to the memory, but not memory.
Robert said:
9 years ago
free(p);
p = NULL;
This is defensive coding style against dangling pointers bugs.
Also on alloc, check the pointer.
if (p != NULL)
p = NULL;
This is defensive coding style against dangling pointers bugs.
Also on alloc, check the pointer.
if (p != NULL)
Kartheek said:
9 years ago
Because of dangling pointer concept. After p= null only to avoid that.
Sowmiya said:
9 years ago
This is also called dangling pointer.
How it will print 1134?
How it will print 1134?
Sarvajeet Suman said:
10 years ago
C compiler provided by IndiaBix online getting random number instead of 1314. Please check it out even in my GCC compiler.
Kuldeep said:
10 years ago
This is also called as dangling pointer. To avoid this situation you must assign p=NULL.
Nagarjuna said:
1 decade ago
Free (p) will leads to an output of garbage if it is of dangling pointer to be assumed other wise 1314 which is address of p.
Ramesh M said:
1 decade ago
After memory chunk of 20 elements allocated the pointer p holds base address of chunk (i.e, 1314) , then free (p) is done so that the memory chunk of 20 elements is available to be reused by the library function again (memory added to main memory). But after freeing is done pointer p is pointing to no where (but holds the address 1314) , so it should be made NULL, on further usage.
Minakshi said:
1 decade ago
I think the answer should be a garbage collection. Because after free memory pointer points to garbage collection.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers