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;
}
1314
Garbage value
1316
Random address
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
57 comments Page 5 of 6.

Kuldeep said:   10 years ago
This is also called as dangling pointer. To avoid this situation you must assign p=NULL.

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.

Sowmiya said:   9 years ago
This is also called dangling pointer.

How it will print 1134?

Kartheek said:   9 years ago
Because of dangling pointer concept. After p= null only to avoid that.

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)

Muzammil said:   9 years ago
The free is a function which will free the data allocated to the memory, but not memory.

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).

Nitesh Singh said:   9 years ago
According to me, the right ans is [D].

Because printf("%u", p);
print the address in p(pointer) location is not fix.

At my first execution the ans >17190928
Ans(2)=>33681424 and third-time different answer.

AnubisYe said:   9 years ago
/* Assume p has address of 1314 */

Please explain this part.

Ganesh gs said:   8 years ago
So here initially p has an address of 1314.

And we're assigning some memory dynamically for the pointer p which will pount to the memory allocated. While looking into the next step we're deallocating the memory so that the memory won't exist but the pointer of address 1314 exists. And therefore while printing it, it gives us the address.


Post your comments here:

Your comments will be displayed after verification.