I am in the beginning stages of writing a fairly large code. I have defined one class as such:
class GPUMD {
private:
double xhi, xlo, yhi, ylo, zhi, zlo;
int numAtoms;
Atom *atoms;
public:
GPUMD();
~GPUMD();
};
The destructor is defined as below:
GPUMD::~GPUMD() {
if(atoms != NULL)
delete [] atoms;
}
Right now, the code does this:
int main(int argc, char *argv[]) {
GPUMD gpumd;
exit(0);
}
I get a glibc detected error: trying to free invalid pointer. Using valgrind, I see that this error traces to my destructor for GPUMD. For some reason, the atoms != NULL test is returning true even though I have not assigned anything to that pointer. Why is that?
EDIT: The constructor is defined as:
GPUMD::GPUMD() {}
Because
atomshas not been explicitly initialised toNULLor a valid pointer in the constructor. Change constructor to:Note that the
atoms != NULLcheck prior to thedelete[]is superfluous asdelete[], ordelete, on aNULLpointer is no-op. The following is safe:As there is a dynamically allocated member in
GPUMDyou need to prevent copying of instances ofGPUMDor implement the assignment operator and copy constructor (see What is The Rule of Three?).As C++, consider using a
vector<Atom>(or avectorof smart pointers) instead which will manage dynamic memory for you.