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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With