I am confused with using free()regarding data structures in C.
If I have the following data structure:
struct Person {
char *name;
int age;
float weight;
float height;
};
I allocate memory for the structure through malloc(), also:struct Person *me = malloc(sizeof(struct Person));
After I have finished using my structure (right before the end of the program), I proceed to free the allocated memory, for example:
free(person_pointer->name);
free(person_pointer);
Releasing the memory that the pointer points to nameis as far as I know, because if I just free person_pointer, I will only free the memory that was allocated to store the data structure and its members , but not the memory pointed to by the member pointers of the structure.
However, with my implementation of valgrind, it seems like the first is free()invalid.
, : , , , -?
EDIT: :
#include <stdio.h>
#include <stdlib.h>
struct Person {
char *name;
int age;
float weight;
float height;
};
int main(int argc, char **argv)
{
struct Person *me = malloc(sizeof(struct Person));
me->name = "Fotis";
me->age = 20;
me->height = 1.75;
me->weight = 75;
printf("My name is %s and I am %d years old.\n", me->name, me->age);
printf("I am %f meters tall and I weight %f kgs\n", me->height, me->weight);
free(me->name);
free(me);
return 0;
}