Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will freeing a structure pointer also free the memory allocated inside of the structure in C?

For example I have this structure:

typedef struct{
    char *var = (char*)malloc(20*sizeof(char));
} EXAMPLE;

EXAMPLE *point = (EXAMPLE*)malloc(sizeof(EXAMPLE));

My first question is, will the memory allocated inside the structure only be allocated when I allocate memory for the EXAMPLE pointer?

My second question, when I use free(point) will the memory allocated for var also be freed?

like image 913
Pedro Avatar asked Sep 05 '25 04:09

Pedro


2 Answers

With this struct:

typedef struct{
    char *var;
} EXAMPLE;

Remember that when you allocate space for the struct, you're allocating space only for the char * pointer. This pointer just points to memory elsewhere. When you free() the struct, you're just freeing the char * pointer, not the actual memory that it points to.

As such, if you make this struct and then malloc() space for the string you want var to point to, you need to free() the string as well as free()ing the struct.


Some code demonstrating how this might work:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct {
    char *var;
} EXAMPLE;

int main(int argc, char *argv[]) {

    // malloc() space for the EXAMPLE struct.
    EXAMPLE *point = malloc(sizeof(EXAMPLE));
    // malloc() space for the string that var points to.
    point->var = malloc(20 * sizeof(char));
    // Copy "Hello!" into this memory (care with strcpy).
    strcpy(point->var, "Hello!");
    // Print it, it works!
    printf("point->var is: %s\n", point->var);

    // Free stuff.
    free(point->var);
    free(point);

    return 0;
}

Also note that we don't cast the result of malloc(), in C you're not meant to. Also note that we free() point->var first before point. This is important because if we free() point first, we lose the pointer to point->var, and we have a memory leak.

like image 133
Daniel Porteous Avatar answered Sep 07 '25 20:09

Daniel Porteous


I'm ignoring the non-compiling code since the question is pretty clear without it ;-)

No. free() does not know the structure of what it is pointing at,so it just frees one "block". If that block has pointers to other malloced memory then they are leaked (unless there is a pointer to those blocks somewhere else).

like image 44
John3136 Avatar answered Sep 07 '25 21:09

John3136