0

I seem to be having a problem with my destructor and/or with freeing allocated memory. Here's my simple code:

void* Init(){
    try {
       Facebook* DS = new Facebook();
       return (void*)DS;
    } catch(std::bad_alloc&) {
       return NULL;
    }
} 

and here's the function releasing the memory allocated by this function:

void Quit(void** DS){
   delete (Facebook*)DS;
   *DS = NULL;
   return;
}

if im simply calling only these 2 functions im getting an invalid delete at the line of the delete, and the memory allocated by the new was lost.

here's the facebook class:

class Facebook {
   private:
   List<Troll*> trollsList;
   AVLTree<PostByLikes> likesTree;
   AVLTree<PostById> idTree;
   int maxPost;
 }

and there's no allocating memory being made in the constructor of this class...

Omri Shneor
  • 965
  • 3
  • 18
  • 34
  • Please take a look at [RAII](http://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii) and do away with code like this – OMGtechy May 06 '16 at 09:47
  • `Quit` should be replaced by a destructor. – erip May 06 '16 at 09:47
  • [OT]: `Init()` can be simplified to `return new (std::no_throw) Facebook();`. – Jarod42 May 06 '16 at 09:57

2 Answers2

2

You're not deleting the Facebook object.

Try this:

void Quit(void** DS)
{
   delete (*DS);
   *DS = NULL;
}
Robert Kock
  • 5,795
  • 1
  • 12
  • 20
1

Try this

void Quit(void** DS){
   Facebook* pDS = (Facebook*)(*DS);
   delete pDS;
   *DS = NULL;
   return;
}
GMichael
  • 2,726
  • 1
  • 20
  • 30