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

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.

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 ?

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

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.

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.


Post your comments here:

Your comments will be displayed after verification.