如何在c ++中解决"Access violating reading location error"?

How to solve "Access violating reading location error" in c++?

本文关键字:violating Access reading location error 解决      更新时间:2023-10-16

大家好,我得到以下错误:

First-chance exception at 0x67887AB7 (SDL2_mixer.dll) in Racing.exe: 0xC0000005: Access violation reading location 0xCCCCCCD4.

我认为问题可能出在指针上,但我在c++方面没有足够的经验来找到它。我希望有人能告诉我我做错了什么,希望我能从中吸取教训:)

试图从我的游戏总线上调用它。

Music Mus;
Mus.SpeelGeluid("crash");

音乐类

bool Music::LoadMusic(){
    //Load music
    Mix_Music *gMusic = NULL;
    gMusic = Mix_LoadMUS("MusicTest.wav");
    Mix_PlayMusic(gMusic, -1);
    bool success = true;
    if (gMusic == NULL)
    {
        printf("Failed to load Music background song! SDL_mixer Error: %sn", Mix_GetError());
        success = false;
    }
    // Load sound effects
    Mix_Chunk *gCrash = NULL;
    gCrash = Mix_LoadWAV("Crash.wav");
    if (gCrash == NULL)
    {
        printf("Failed to load scratch sound effect! SDL_mixer Error: %sn", Mix_GetError());
        success = false;
    }
    return success;
}
void Music::SpeelGeluid(string soundname){
cout << soundname << endl;
if (soundname == "crash")
{
    try
    {
        Mix_PlayChannel(-1, gCrash, 0);
    }
    catch (int e)
    {
        cout << "An exception occurred. Exception Nr. " << e << 'n';
    }
} 
else
{
}   }

感谢您抽出时间

您有两个主要问题:

首先,先使用gMusic,然后再检查它是否为NULL
这可能会使Mix_PlayMusic崩溃,实际上意味着编译器可能会优化稍后的NULL检查。

其次,也很可能是问题的原因,您将gCrashgMusic声明为LoadMusic中的局部变量
根据名称以及您在SpeelGeluid中使用gCrash,我有根据的猜测是,您还有两个全局变量,或者可能是成员变量,它们的名称与您打算存储加载文件结果的名称相同。

您的局部变量隐藏了这些全局变量,而您只是在修改局部变量。

删除线路

Mix_Music *gMusic = NULL;

Mix_Chunk *gCrash = NULL;

去掉这些局部变量。

定义全局变量时,请将其初始化为NULL

分配完指针后立即检查指针,并对其进行适当处理。你差点做到:

gMusic = Mix_LoadMUS("MusicTest.wav");
Mix_PlayMusic(gMusic, -1); // <- You're using the pointer here before you check it
bool success = true;
if (gMusic == NULL) // <- this needs to be immediately after assignment

这只是你指出的代码。也有可能您错过了来自SDL2_mixer.dll的通用初始化调用。

一定要调试它,一行一行地检查,这样你就知道是哪个位导致了错误。