C++ allocates previously reserved memory when using new Obj2() inside constructor of Obj1?

65 views Asked by At

I have a Class "Grid" which declares a 2-dimensional array of pointers to objects of class "Cell" as property. When I instantiate an object of "Grid" I see in the debugger, that the constructor's code which initializes the array calling "new Cell(p1, p2)" inside a loop produces pointers to Cells which lie inside the allocation for the array, thus corrupting the array of pointers.

Here some extracts of the code:

class Cell {
    public:
        Cell( int a, int b );
}
class Grid {
    public:
          Grid(); 
          Cell * g[6][7];
}

// code:

Grid::Grid() {
  // g is allocated to address x'13d1-19b8 (extending for 42*4=168 bytes)
    for ( int r=0; r<6; r++ )
    {
        for ( int c=0; c<7; c++ )
        {
            g[r][c] = new Cell( r, c );  // g[0][0] now contains x'13d1-19d8 which is INSIDE g[][] !?!?!
        }
     }
.....
}

Can anybody tell me what's going on or what I'm doing wrong?

1

There are 1 answers

0
Mark On

I've rebuilt the project piece by piece, trying to descover which part of the code causes the corruption. However I couldn't reproduce the error. I now have what looks to my eye an identical copy of the original code and it works just fine. (The original one still fails.) Can't see where I made the mistake in the first attempt, but I'm happy to be able to progress.

Thanks to those (@Cameron) who tried to help and maybe some day @Dieter will explain to me why he down-voted my question... ;)