Reputation: 114
Currently i am dynamically allocating memory for a structure, after which i am dynamically allocating memory for one of its members. My question is should i free the member too, or only the structure and why?
#include <stdlib.h>
struct test{
char *test_member;
};
int main(){
struct test *new_test;
// Allocating memory for structure and its member
new_test = (test*)malloc(sizeof(test));
new_test->test_member = (char*)malloc(80);
// Freeing struct member and struct
free(new_test->test_member);
free(new_test);
return 0;
}
Upvotes: 1
Views: 78
Reputation: 52
Since variables in the structure are allocated, you need to free them first, and free the structure.
It is same as dynamic allocate of 2D array A. when you wanna free 'A' you need to free A[i] first and then free A to prevent memory leak..
So your code is correct
Upvotes: 1