Saturday, May 26, 2018

c++ - Double free or corruption when using template

After I run the code bellow, I get a runtime error "double free or corruption".



If I get rid of the destructor content (the delete) it works fine. What's wrong?



The message inside the destructor helped me to find that it is related to the destructor of the variable element, but I know really know how to fix it.




#include 
#include
#include
/// First test class
class test_t {
public:
uint16_t *number;
uint16_t& get_number(){return number[0];};

test_t(){number = new uint16_t[16];};

~test_t(){
printf("DESTOY test\n");
delete [] number;
};

test_t& operator=(const test_t& other){
if (this != &other) {
memcpy( number, other.number, 16 );
}
return *this;

}
};

/// Circular Buffer template
template
class circular_buffer_t
{
public:
/// Control variables
uint32_t beg_index, end_index, size, capacity;

CB_TYPE *data;

/// Methods
circular_buffer_t(){
this->beg_index = 0;
this->end_index = 0;
this->size = 0;
this->capacity = 0;

this->data = NULL;

};

~circular_buffer_t(){
printf("DESTOY CB\n");

if (this->data != NULL) {
delete []data;
}
};


CB_TYPE& operator[](uint32_t index){
uint32_t position = this->beg_index + index;
if (this->end_index >= this->capacity) position = 0;

return data[index];
};

CB_TYPE operator[](uint32_t index) const {
uint32_t position = this->beg_index + index;
if (this->end_index >= this->capacity) position = 0;


return data[index];
};

void allocate(uint32_t elements){
this->capacity = elements;
this->data = new CB_TYPE[this->capacity];
if (this->data == NULL)
printf("Could not allocate the circular buffer size.\n");
};



int32_t push_back(CB_TYPE new_element){
int32_t virtual_position = -1;

this->size++;
memcpy(&this->data[end_index], &new_element, sizeof(CB_TYPE));

this->end_index++;
if (this->end_index >= this->capacity) this->end_index = 0;


virtual_position = this->size - 1;

return virtual_position;
};
};


int main()
{

circular_buffer_t cb;
cb.allocate(10);

{
test_t element;
cb.push_back(element);
} // This emulates the call for the destructor from "element"


printf("done %d", cb[0].get_number() );

return 1;
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...