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.

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.

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

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.

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.

Premnath.N said:   1 decade ago
We have declared the function free(p) ; but we didn't define that function, so it will skip that line and print the address of p. If we define the given function means it will return the value.

Boobal said:   1 decade ago
Free will deallocate the memory but the address of p still points to the same (invalid) location and not the null value. The dereferencing of the pointer will give unpredictable values.

Bharrath said:   1 decade ago
Yes, the free () function will free the memory of p array but not the pointer so still it points the address of p that's why it prints 1314 as assumed in the program.

The Guide said:   1 decade ago
free() deletes the memory that is pointed by p but not the address of p i.e in the above example the free() deletes a memory that p points to an integer.

Prasad said:   1 decade ago
Eventhough the array is deleted the pointer still pointing to memory location in heap area so we must assign null value to dangling pointer.

Hemant singh said:   1 decade ago
We are assigning the address to p not the value where as the free() function clear the content of the memory location not the address.


Post your comments here:

Your comments will be displayed after verification.