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.

Vikas Sharma said:   1 decade ago
Here, memory allocated by malloc function gets deleted, but the pointer still holds the base address of the deleted memory block.

Gautam said:   1 decade ago
When you call free(p) then it will deallocate the address 1314. Please explain it.

Mohit Dwivedi said:   1 decade ago
When you call free() it will de-allocate the address dynamically assigned via malloc function. Here pointer p is pointing to the first address of set of 20 memory allocation which will be dynamically allocated. Now when we use free() this dynamic allocation ended but not the existence of pointer. You can allocate another set of value using the same pointer variable(p). So the address of pointer will remain the same even after using free().

Sundar said:   1 decade ago
@Mohit Dwivedi

What you said is exactly correct.

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.

Maheshwaran said:   1 decade ago
free() function will free the dynamic memory space for pointer of p.

But declaration of integer *p has been specified by some other address. That will not free by that free() function.

free() - It releases the dynamically allocated memory not declared memory.

Anjali said:   1 decade ago
Well , actually p holds the starting address of the array.......free funtion will delete the memory which is allocated for that array.......say array is of size 10 and it is of integer type so it should require 20 bytes of memory as "int" occupies 2 bytes of memory (ofcourse it depends on compiler). So when we free the pointer it doesn't mean that we are deleting the pointer . We are deleting the memory which is allocated to the pointer i.e, 20 bytes of memory (according to my example).........so p has the address 1314 itself.

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.

Ashu said:   1 decade ago
Actually the pointer is not deleted it is the space which is deleted.

Sweety said:   1 decade ago
Give me clear explanation.


Post your comments here:

Your comments will be displayed after verification.