Sunday 3 November 2019

c++ - Deleting objects with heap members

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.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...