-1
typedef struct A
{
    int* whatever;  
} A;


int main(void)
{
    A* foo = (A)malloc(sizeof(A));
    foo->whatever = (int)malloc(sizeof(int));
    free(A); // leak? (foo->whatever)
    return 0;
}

Do I have to free each component of a struct / composite data type, or can I just free the struct?

Lemmons
  • 1,738
  • 4
  • 23
  • 33

2 Answers2

3

Anything that is malloc'd needs to be freed

Lawrence Aiello
  • 4,560
  • 5
  • 21
  • 35
1

For each malloc in a program, there must be a free. That's the rule, plain and simple.

Since you malloc twice, free twice.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • And do it in the correct order. Last memory malloced should be first memory freed. – Zan Lynx Nov 10 '14 at 21:02
  • @ZanLynx: That's less important. Objects can outlive other objects. – nneonneo Nov 10 '14 at 21:02
  • Not when they are nested. If the container object is free'd first then it is invalid to use its pointer to get at the pointer inside. – Zan Lynx Nov 10 '14 at 21:04
  • @ZanLynx: Yes, but that's not a _general_ rule about `malloc` and `free`. You could just as easily copy the contained object's pointer somewhere and use that to free it later. – nneonneo Nov 10 '14 at 21:07
  • It's important in this case...if you free the struct first, the pointer inside is no longer valid and can't be freed. – Lee Daniel Crocker Nov 10 '14 at 21:07