Ricky Ma
Ricky Ma

Reputation: 3

Read Violation when Accessing 2D array

I got a really weird read violation error when I try to access the addresses that are supposed to be inside a 2D array. Please read several lines of my code:

Class class : public SuperClass
{ 
public:
    bool checkDirt(int x, int y)
    {
        if(DirtField[x][y] != nullptr) //read violation error given here
................

private:
    Dirt* DirtField[64][60];
}

The DirtField 2D array consist of pointers to Dirt objects and nullptrs

When I tried to debug the program, it tells me the x and y are always well with in the bound of the 2D array, say x=21, y=14. But no matter what value is x and y I always get the error.

Please help. Thanks a lot!

Upvotes: 0

Views: 104

Answers (1)

Christophe
Christophe

Reputation: 73376

Let's suppose that the debugger gives the correct place of the access violation and let's proceed by elimination:

  • DirtField is a fixed 64x60 array. So DirtField can't be nullptr, and the read access error can't come from allocation of DirtField.
  • if you have checked that x and y are both within range, the read access error can't come from an out of bound access to the array either.
  • DirtFiled[x][y] contains a pointer to Dirt that you compare with anothers pointer without derefencing any of them. So it couldn't be an issue with the Dirt class either, or the content of the DirtField array.

The only problem left, would be that the object on which you've called checkDirt() is itself invalid. Something like:

Class *myobject;  // unitinialized pointer 
myobject->checkDirt(21,14);  

Upvotes: 1

Related Questions