如何在c ++中解决"Access violating reading location error"?
How to solve "Access violating reading location error" in c++?
大家好,我得到以下错误:
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
检查。
其次,也很可能是问题的原因,您将gCrash
和gMusic
声明为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的通用初始化调用。
一定要调试它,一行一行地检查,这样你就知道是哪个位导致了错误。
相关文章:
- 将数组信息存储到 c++ 向量中有一个"Access violation reading location"
- 为什么调试器引发"read access violation. this was nullptr"异常?
- 在 Microsoft Access SQL 中调用自定义 DLL 函数时传递的内存地址无效
- Simulink "Access Violation"写入 C++ lambda 函数捕获列表中的 PWork 变量
- Qt QXmlStreamReader Access Violation
- "Access is Denied" U盘上的创建文件()
- 指向 std::unrodered_map 中元素的指针返回'Read access violation'
- 例外:'Access violation reading location'
- 向量数组"Cannot access memory at address"
- Windeployqt不会运行,"Access is denied."
- 我在发布模式下运行时收到"Access violation reading location"错误 - C++
- Access C++ Enum from Swift
- Java 本机访问代码错误:"Invalid memory access"
- 如何获得私人会员的"read access"?
- 将数据添加到 CArray 会产生错误"cannot access private member declared in class 'CObject'"
- C++:分析包含表达式的字符串"access to the multidimensinal array"
- 如何修复我的 c++ 毕达哥拉斯三重查找器中的'access violation reading location'错误?
- C 和WXWIDGETS DLL创建并与Microsoft Access一起使用
- 矩阵 - "Access violation writing location 0x00900B0C" - C++ 中的错误
- 如何在c ++中解决"Access violating reading location error"?