0xC0000005:访问违规读取整数的位置?

时间:2011-05-28 17:11:49

标签: c++ class pointers

通常人们在处理指针,数组,结构等时都会收到这些错误。我在类中的每个整数上都得到它,这让我很困惑。我确定我只是缺少一些小的技术细节(我对此有点新鲜)。

确切的错误是:

First-chance exception at 0x003e6616 in Mine.exe: 0xC0000005:
    Access violation reading location 0x00000008.
Unhandled exception at 0x003e6616 in Mine.exe: 0xC0000005:
    Access violation reading location 0x00000008.

代码在此类方法的第一行中断:

void Grid::Move(int x, int y)
{
this->offX+=x;
this->offY+=y;
for (int i=0;i<2;i++)
    for (int k=0;k<2;k++)
        BitmapSetxy(chunks[i][k]->map,this->offX,this->offY);
}  

这是Grid的构造函数:

Grid::Grid()
{
totalW =320*2;
totalH = 320*2;
offX = 0;
offY = 0;

//Fill the chunks array with Maps to be used
for (int i=0;i<2;i++)
    for (int k=0;k<2;k++)
        chunks[i][k] = new Map(i*320,k*320);

//Everything starts as dirt
for (int x=0;x<(320*2)/20;x++)
    for (int y=0;y<(320*2)/20;y++)
        blocks[x][y] = bType::Dirt; 
}

头文件:

#ifndef MapDef
#define MapDef

#include "Map.h"

class Grid
{
private:
int totalW, totalH;
int offX, offY; 
public:
enum bType
{
    Blank,
    Dirt,
    Copper
};

Map * chunks[2][2];
bType blocks[32][48];   
void RemoveBlock(int x, int y);
bType GetBlockAt(int x, int y);
int GetAbsolutePosition20(int);
int GetMapIndex(int);
int GetChunkRelative(int,int);
bType GetBlockBelow(int x, int y);
bType GetBlockAbove(int x, int y);
bType GetBlockSide(int x, int y, bool isRight);
void Move(int x, int y);
Grid();
};

#endif

当查看Grid totalW的当前实例的locals视图时,totalH,offX,offY都显示CXX0030错误,但这两个数组完全正常。到底发生了什么?

编辑:

网格指针的定义存储在一个单独的小名称空间中,该名称空间用作静态类:

namespace Engine
{       
static Grid * grid;
static Player * player;
}

它实际上是在主cpp文件中创建的:

//Initialize engine
Engine::grid = new Grid();
Engine::player = new Player(160,240);

这是在另一个名为Player

的类中调用它的摘录
    if (y>392 && y<480 && x>75 && x<152)
    {
        printf("Right");
        Engine::grid->Move(20,0);
    }

编辑2:

对不起,我忘了从引擎中的网格声明中删除“static”关键字。我相信这就是造成这个问题的原因。

2 个答案:

答案 0 :(得分:10)

根据错误消息,您的代码正在尝试访问地址0x00000008,这非常接近0.这意味着您可能在某处有一个类型为Grid *的空指针,并且您正在调用它上面的函数。

您应该确保指针不为null,或者检查它。例如:

Grid * grid = ...;
if (grid == NULL){ return; }
grid->move(0,1);

请注意NULL与0相同。

答案 1 :(得分:3)

'this'的价值是多少?您是否尝试取消引用指向Grid实例的空指针?

相关问题