为什么我的阵列超出范围?

时间:2013-09-16 23:00:59

标签: c++ arrays visual-studio-2010 scope

这是一个模拟器,但现在我只是加载ROM。我不明白为什么我的代码给我一个中断异常错误。在bufferGame函数之后,gameBuffer变量超出了范围。我可以在该函数中调用gameBuffer [0]等,但是一旦我创建另一个函数来调用数组,它就会给我:SNES Emulator.exe中的0x0093303A处的未处理异常:0xC0000005:访问冲突读取位置0x00000008。请帮忙!

部首:

class CGame
{
public:
CGame(char* passed_gamePath);
~CGame(void);

void loadGame(char* gamePath);
void closeGame();
BYTE* getBufferedFile();
int getGameSize(FILE* game);
void bufferGame(FILE* game);
void printHexBytes(int offset, int amount);

private:
    int gameSize;
    FILE* game;
    BYTE* gameBuffer;
};

CPP档案: 构造:

CGame::CGame(char* passed_gamePath)
{
game = NULL;
gameSize = 0;
gameBuffer = NULL;
loadGame(passed_gamePath);
bufferGame(game);
}

loadGame:

void CGame::loadGame(char* gamePath)
{
if ((fopen_s(&game, gamePath, "rb")) == 0)
{
    std::cout << "File opened successfully!" << std::endl;

    gameSize = getGameSize(game);

}
else
{
    std::cout << "Could not open file." << std::endl;
}
}

bufferGame:

void CGame::bufferGame(FILE* game)
{
gameBuffer = new BYTE[gameSize];

    if (fread_s(gameBuffer, gameSize, 1, gameSize, game) != 0)
    {   
        std::cout << "Read file successfully!" << std::endl;
    }
    else 
    {
        std::cout << "Error reading file." << std::endl;
    }   
}

*编辑:这是附加代码,因为你们认为上述内容是正确的。

模拟器在main中实例化。构造函数实例化Game的实例。然后调用printHexBytes,这是我在读取gameBuffer时遇到的错误。 (顺便说一句,我已将游戏(变量)重命名为gameFile以防止混淆。)

模拟器构造函数:

CEmulator::CEmulator(void)
{

CGame* Game = new CGame("SuperMarioWorld.smc");
p_Register = 0x00;

}

主档案:

int main (void)
{
CEmulator* Emulator = new CEmulator();


Emulator->getGame()->printHexBytes(0x0FF, 9);

std::cin.get();

delete Emulator;
return 0;
}

打印Hex字节(CGame的一部分):

void CGame::printHexBytes(int offset, int amount)
{
for (int i = offset; i < (offset + amount); i++)
{
    printf("%X ", gameBuffer[0]);   
}
}

1 个答案:

答案 0 :(得分:3)

您的问题出在CEmulator构造函数中:

CGame* Game = new CGame("SuperMarioWorld.smc");

您正在创建一个新的CGame,将其存储在名为Game local 变量中,然后在函数返回时将其丢弃。也许你打算把它存放在其他地方?