1

If I have the next function

Stack *construct_stack(void) {
  Stack *instance = (Stack *) malloc(sizeof(Stack));

  // Stuff...

  return instance;
}

It's sort of "constructor". But I'v been having problems with the "destructor".

If I do this I get an error.

void destruct_stack(Stack **st) {
  // Stuff...

  free(st);
}

Some idea?

mishelashala
  • 531
  • 2
  • 5
  • 12

2 Answers2

3
void destruct_stack(Stack **st) {
  // Stuff...

  free(*st);//free the pointer which st points to
  *st = NULL;//set it to null
}

And You don't need to cast the result of malloc: Do I cast the result of malloc?

Community
  • 1
  • 1
Viktor Simkó
  • 2,607
  • 16
  • 22
2
void destruct_stack(Stack **st)

Here st is pointer to pointer(i.e instance) to which you allocate memory (st holds address of pointer instance).

 free(st); // you didn't allocate memory to st therefore gives error

So you should free *st like this

   free(*st);
   *st=NULL;  // just a good practice 

Or another way instead of address of the pointer(i.e &instance) you can pass the pointer instance itself and then free it but you will need to change the type of parameter which is passed to function.

ameyCU
  • 16,489
  • 2
  • 26
  • 41