C Programming - Memory Allocation - Discussion
Discussion Forum : Memory Allocation - Point Out Correct Statements (Q.No. 3)
3.
Point out the correct statement which correctly free the memory pointed to by 's' and 'p' in the following program?
#include<stdio.h>
#include<stdlib.h>
int main()
{
struct ex
{
int i;
float j;
char *s
};
struct ex *p;
p = (struct ex *)malloc(sizeof(struct ex));
p->s = (char*)malloc(20);
return 0;
}
Discussion:
10 comments Page 1 of 1.
Ajith said:
8 years ago
First, need to free the s then free the p to free.
Ajeet singh said:
8 years ago
What is the use of molocius fanction here?
Skyyo said:
9 years ago
Option B is correct, I agree.
Surya_09 said:
1 decade ago
Option B is correct,
First we have to free "p->s" since this is the member of the "struct p".
If we make first "p" free then we will not be able to access "s" as there will be no "struct p" remain although s is still pointing to some location which I have to make free as question says.
First we have to free "p->s" since this is the member of the "struct p".
If we make first "p" free then we will not be able to access "s" as there will be no "struct p" remain although s is still pointing to some location which I have to make free as question says.
Suny said:
1 decade ago
What will be the size of the structure here ?
Kavish Kansal said:
1 decade ago
@Manish. Option A also says the same thing as that said by option B. Why have we not chosen Option A?
Chiluku naidu said:
1 decade ago
This is very logical questions and I have many doubts about learning this questions.
Divya said:
1 decade ago
Answer is exactly correct but it may give different answer based on compilers.
Manish said:
1 decade ago
Option b is correct because s is pointer variable of structure so it can be aceesd by p->s so free done by free(p->s)and p can be freed by free(p)
Karthik said:
1 decade ago
Option A is incorrect because the memory acquired by the structure is returned first so it results in a memory leak since the reference of p is lost after releasing the memory.
Option C is wrong since it is releasing oly the memory acuired by the variable in the structure not the memory of the structure.
Option D is also results in memory leak since it is releasing oly the memory acquired by the structure.
Option B is correct.
Option C is wrong since it is releasing oly the memory acuired by the variable in the structure not the memory of the structure.
Option D is also results in memory leak since it is releasing oly the memory acquired by the structure.
Option B is correct.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers