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?

3
  • Why you pass pointer to pointer ? just pass a pointer and free it .
    – ameyCU
    Commented Sep 5, 2015 at 6:14
  • 1
    free(*st);*st=NULL;
    – BLUEPIXY
    Commented Sep 5, 2015 at 6:14
  • 'Cause my code looks like this: Stack *s = construct_stack(); // Stuff... destruct_stack(&s); Commented Sep 5, 2015 at 6:21

2 Answers 2

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?

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.