Home > Software design >  How to free member variable malloc memory in a destructor
How to free member variable malloc memory in a destructor

Time:10-10

//Constructor

    page_frames = (Page*) malloc(page_count*PAGE_SIZE);
    for (uint32_t i = 0 ; i < page_count;   i) {
        page_frames = new Page[PAGE_SIZE];
        page_frames  ;
}

//Destructor

    free(page_frames)

page_frames is a member variable of type Page*. Whether I try to deallocate the memory in the destructor, valgrind returns "Invalid free() / delete / delete[] / realloc()".

I would like to free up the memory left by malloc() to prevent any leaks. Is there a way to free memory of a member variable in the class destructor?

CodePudding user response:

I'm assuming page_frames is a member variable declared as Page* page_frames in your class declaration. And you are attempting to create an "array of Pages"

This:

page_frames = (Page*) malloc(page_count*PAGE_SIZE);
for (uint32_t i = 0 ; i < page_count;   i) {
    page_frames = new Page[PAGE_SIZE];
    page_frames  ;
}

Has several issues. The initial malloc'd page_frames gets overwritten on the first iteration of the loop by the new call. The other issue is that pages_frames itself is getting adjusted to something else each time you invoke page_frames . Hence, your free(page_frames) statement doesn't pass the value that was returned from malloc.

Option 1

This closer to what you want:

page_frames = (Page*) malloc(page_count*PAGE_SIZE);
for (uint32_t i = 0 ; i < page_count;   i) {
    page_frames[i] = {}; // default construct a page
}

But that's using C allocation semantics instead of C style allocations for objets. We can do better.

Option 2

Keep to using C allocation semantics.

This is even simpler and doesn't require a for-loop

page_frames = new Page[page_count];

And your corresponding destructor statement is this;

delete [] page_frames;

Option 3

No explicit allocation/deletion require. Let the C collection class library do the hard work for you.

Declare page_frames as std::vector<Page>.

And your constructor is just this:

page_frames.resize(page_count);

And no destructor work needed.

  •  Tags:  
  • c
  • Related