Deleting objects with heap members

84 Views Asked by At

I am working on a bitset implementation. The bitset uses an array of unsigned long long to store the bits.

class bitset{
    typedef unsigned long long uint64;
    uint64* bits;
    ...
}

Since I need this bitset to store a large about of data, I am finding that it works best when I initialize the array of uint64 using the new keyword to build it on the heap.

bitset::bitset(int n_bits){
    if (n_bits % 64 !=0) size (n_bits / 64) + 1;
    else size = n_bits / 64;
    this->data = new uint64[size];
}

Doing do allows my program to consistently allows my whole program to access the array of bits. The One issue I'm running into is that my destructor doesn't seem to be able to delete the data

bitset::~bitset(){
    delete[] this->data;
}

Working without the destructor, I get a memory leak (as expected), with the destructor I get a runtime error Error in `./a.out': double free or corruption (out): I have tried googling this to no avail. I am fairly new to c++, so any insight on stack/heap behavior within classes would be appreciated.

1

There are 1 best solutions below

2
eerorika On

You can use the vector container:

class bitset{
    ...
    std::vector<uint64> bits;
    ...

Vector takes care of memory allocation so that you don't get problems with accidentally deleting memory more than once or accidentally leaking the memory.


P.S. unsigned long long is not guaranteed to be exactly 64 bits. It is allowed to be bigger than that. If that is crucial detail to your program, then you should use std::uint64_t from the standard library instead. This is mostly only relevant to future compatibility.