I am implementing a double-join class that stores "buckets" (nodes), each of which contains a predetermined number of characters. Each bucket stores a pointer to the next and previous bucket, and the list class (BucketString) stores a pointer to the head bucket. I am compiling with g ++ that throws an error
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc make: *** [run] Aborted (core dumped)
whenever I run the code and add a character string to the list using the following add method, which is contained in my bucket class, and if necessary is called from the list boxโs own methods.
the code:
std::size_t bucketSizeB; int filled; char* str; Bucket* next; Bucket* prev; Bucket::Bucket() : bucketSizeB(7), str(new char[7]), next(NULL), prev(NULL), filled(0) {} Bucket::Bucket(std::size_t bucketSizeB_) : bucketSizeB(bucketSizeB_), str(new char[bucketSizeB]), next(NULL), prev (NULL), filled(0) {} Bucket::Bucket(const Bucket& rhs) : bucketSizeB(rhs.bucketSizeB), next(rhs.next), prev(rhs.prev), filled(rhs.filled) { for (int i = 0 ; i < (int) bucketSizeB ; i++) { str[i] = rhs.str[i]; } } void Bucket::add(std::string line) { int diff = bucketSizeB - filled; //if the bucket is already partially filled std::string tmp = line.substr(0, diff); for (std::size_t i = 0 ; i < tmp.length() ; i++) { str[filled] = line[i]; ++filled; } if (line.length() > bucketSizeB) { next = new Bucket(bucketSizeB); next->prev = this; next->add(line.substr(diff, line.length()-diff)); } } Bucket::~Bucket() { if (prev) { if (next) { prev->next = next; } else { prev->next = NULL; } } if (next) { if (prev) { next->prev = prev; } else { next->prev = NULL; } } delete [] Bucket::str; }
When an error occurs, the add method is called from the member 'list' method, which works as follows:
void BucketString::append (std::string& line) { length += line.length();
Header file for bucket class:
#include <cstddef>
wesrobin
source share