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 2 of 6.

Akarsh bajpai said:   1 decade ago
When we call free() the memory allocated to the first 20 elements with the help of pointer gets deleted but not the existence of the base address of the pointer. Pointer will always remain there you can reallocate memory with the help of pointer, or use pointer in any respect you want.

Chandrabhan said:   1 decade ago
There is no any option in output list. O/P = 145711224.

Minakshi said:   1 decade ago
I think the answer should be a garbage collection. Because after free memory pointer points to garbage collection.

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.

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.

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)


Post your comments here:

Your comments will be displayed after verification.