If you think I did not include anything potentially useful in this question feel free to comment and ask about it.
I have a simple Dna struct with 2 constructors where I allocate an array of int and a destructor where I delete this array (I do not refence this array anywhere else in the code). This is pretty simple, but it produces an invalid free.
#ifndef __DNA_H__
#define __DNA_H__
#include <random>
#include <cstddef>
#include "constants.hpp"
template <class URNG>
struct Dna
{
Dna(const Dna& lhs, const Dna& rhs, URNG& urng)
{
_data = new int[c_dnaLength];
std::bernoulli_distribution startDistrib(0.5);
std::bernoulli_distribution mutatDistrib(c_mutatP);
std::bernoulli_distribution crossDistrib(c_crossP);
const Dna * ptr = (startDistrib(urng)) ? &lhs : &rhs;
for (std::size_t i = 0; i < c_dnaLength; i++)
{
if (crossDistrib(urng))
{
ptr = (ptr == &rhs) ? &lhs : &rhs;
}
_data[i] = mutatDistrib(urng) ? 1 ^ ptr->_data[i] : ptr->_data[i];
}
}
Dna(URNG& urng)
{
_data = new int[c_dnaLength];
std::uniform_int_distribution<int> dnaDistrib(0, 1);
for (std::size_t i = 0; i < c_dnaLength; i++)
{
_data[i] = dnaDistrib(urng);
}
}
~Dna()
{
delete[] _data;
}
int* _data;
};
#endif
Here is a bit of the valgrind log :
==5084== Invalid free() / delete / delete[] / realloc()
==5084== at 0x4C2C05C: operator delete[](void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5084== by 0x40263F: Dna<std::mersenne_twister_engine<unsigned long, 32ul, 624ul, 397ul, 31ul, 2567483615ul, 11ul, 4294967295ul, 7ul, 2636928640ul, 15ul, 4022730752ul, 18ul, 1812433253ul> >::~Dna() (dna.hpp:47)
The destructor get call when I erase a member of a std::list of a class that contain a Dna struct member...so that's a bit complicated without showing large piece of code.