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.