Confused by malloc and free behavior

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;
}
+5
4
me->name = "Fotis";

/* ... */

free(me->name);

:

1 malloc = 1 free

malloc me->name, free.

BTW, me->name const char *.

+5

    me->name = "Fotis";

name malloc, , , .

: , malloced.

.

- :

me->name = strdup("Fotis");

strdup malloc (. ), , .

+1

, , .

Also make sure that you free the participants before you release the structure.

An easy way to remember is to release them in the reverse order in which you highlighted.

+1
source

The problem is that you did not actually specify the char * name inside your structure.

struct Person *me = malloc(sizeof(struct Person));
me->name = strdup("Fotis");
...
free(me->name);
free(me);
return (0);

When you write this

me->name = "Fotis";

You are not actually malloc, the name of the pointer points to a type stack variable const char *that is not malloc'ed.

+1
source

All Articles