Search code examples
c++arraysmemory-leaksstructdelete-operator

How to free an array of structure and objects in C++?


The structure of the program is as such, there is a header file manager.h in which C++ class is defined with data members and member functions. Then in a manager.C file the member functions are implemented.

I've defined 3 structs in the .c file.

#define HTSIZE 7

struct Node
{
int value;
int page;   
struct Node *next; 
};

struct Node *hashtable[HTSIZE];


struct lruNode{
int value;
struct lruNode *next;
struct lruNode* head;
struct lruNode* tail;

};

struct lruNode* lruhashtable[HTSIZE];
struct lruNode* lruTrackHead;
struct lruNode* lruTrackTail;


struct mruNode{
int value;
struct mruNode *next;    
 };

 struct mruNode* mruTrackHead=NULL;
 struct mruNode* mruhashtable[HTSIZE];

The data members of class are as follows: Class Name:Page

Class Name:Frame

Class Name:Manager

All the structs are declared in manager.C

manager.h has the following data members.

Page* pagePool;
Frame* framePool;

In manager.C I'm defining them as

pagePool=new Page[n];
framePool=new Frame[n];

In the destructor for manager.C

I'm doing

delete[] pagePool;
delete[] framePool;
*hashtable=NULL;
*lruhashtable=NULL;
*mruhashtable=NULL;

The structs here are global and not part of the class as such. This is part of my homework. The problem is in my test-cases I'm carry forwarding the previous test case values.

I did an edit to set the pointers the way they are. Now the first value in the array for all array of pointers to struct is null.

Still the array of pointers to objects are not freed up. Can someone comment on that?

Edit

On iterating through a loop, the pointers are freed.

But still the array of pointers to objects are not?


Solution

  • when you call

    free(hashtable);

    you dealocate memory alocated for an array of

    int value;
    int page;   
    struct Node *
    

    but the memory alocated for structure that is pointed by Node is note dealocated.

    The main idea is to dealocate from the "deepest pointed" structure to top. So try to do a bottom up dealocation ,in reverse order that it was alocated.