Double arrays occupy overlapping memory

I'm coding in C++ on MacOS 10.5 and I was debugging a BAD_EXEC_ACCESS and I came across a strange issue. I noticed that an array entry was consistently being augmented by a fixed amount so I went through and looked for anywhere in the code that I manipulated that entry and couldn't find a single place where this addition could have occurred.

So, I set a watchpoint on the memory and found, much to my surprise, that it was happening during a method in a completely different class. More or less, here is what is happening.

In a class, table.cpp, the constructor initializes a dynamic array called LjFl, zeros it out and stores something in the first element (the other elements also get values but that happens elsewhere):

1
2
3
4
LjFl = new double[nl];
for (int i=0; i<nl; i++)
	LjFl[i] = 0;
LjFl[fp->getLanePtr()->getIndex()] += fp->getLength()*fp->getLanePtr()->getLaneEffect();


Right after this, gdb tells me:
1
2
3
4
(gdb) p LjFl
$1 = (double *) 0x401020
(gdb) p LjFl[0]
$2 = 535


and 535 is the exact value I want.

Now if I set a write watchpoint on the value at 0x401020, it goes off in the middle of a method in another class, dish.cpp. It goes off during:

1
2
3
4
void dish::addPatron(patron* np) {
	LjFl[np->getLanePtr()->getIndex()] += np->getLength()*np->getLanePtr()->getLaneEffect(); 
	diners += np->getData();
}


A couple notes: both classes have private members named LjFl, but I don't think that should be a big deal, right? I earlier allocated dish.LjFl with
1
2
3
4
LjFl = new double[nl]; 
for (int i=0; i<nl; i++) {
	LjFl[i] = 0;
}


Anyway, when my watchpoint hits I can check with gdb:
1
2
(gdb) p LjFl
$3 = (double *) 0x400ff0

Which, if you do the arithmetic, means that
1
2
p &LjFl[6]
$2 = (double *) 0x401020

and that is exactly the address of my earlier array!

This actually happens numerous times because I have a whole lot of dish and table objects, and it happens for each and every one of them. Any clues as to what's going on?
You likely have either a buffer overrun or a double-free error.

Do your dish and table classes have proper copy constructors, assignment operators and destructors?

Have you considered using vector<double> in place of your dynamically allocated arrays? This would avoid potential allocation/deallocation errors and you could then replace the unchecked array operator with the bounds-checked at() method.
I don't actually need any copy constructors or assignment operators for these classes because I instantiate my objects early and then pass them around via pointers. The destructors are all good as far as I can tell.

I think I will try replacing the arrays with vectors and see what happens.
copy constructors, assignment operators and destructors: If you need one, you probably need all three (or you need to explicitly disable copying).
Topic archived. No new replies allowed.