C++ 解构sf::Image数组时堆损坏
所以我尝试在SFML中为sf::Image制作一个淡入淡出过渡动画,我有一个小问题 当我没有注释掉下面调用的函数时,在解构图像时,C++ 解构sf::Image数组时堆损坏,c++,image,pixel,sfml,C++,Image,Pixel,Sfml,所以我尝试在SFML中为sf::Image制作一个淡入淡出过渡动画,我有一个小问题 当我没有注释掉下面调用的函数时,在解构图像时,main()的末尾会出现一个错误 “Windows已触发断点。这可能是由于损坏 “一堆。” 发生这种情况的行包含代码GLCheck(glDeleteTextures(1,&Texture)) 为什么会发生这种情况,为什么只有在运行CreateTransition()时才会发生这种情况? 还有一个注意事项:当我注释掉aray[I]=aray[0]时,中断不会发生。 我在
main()
的末尾会出现一个错误
“Windows已触发断点。这可能是由于损坏
“一堆。”
发生这种情况的行包含代码GLCheck(glDeleteTextures(1,&Texture))代码>
为什么会发生这种情况,为什么只有在运行CreateTransition()时才会发生这种情况?
还有一个注意事项:当我注释掉aray[I]=aray[0]
时,中断不会发生。
我在下面发布了这个函数
void CreateTransition(sf::Image& start, sf::Image animationArray[numbImgs]){
animationArray[0] = start;
void threadFunc(void* imgArray);
sf::Thread thread(threadFunc, reinterpret_cast<void*>(animationArray));
thread.Launch();
thread.Wait(); // comment this out once I get the code working
}
void threadFunc(void* ptr){
sf::Image* aray = reinterpret_cast<sf::Image*> (ptr);
sf::Color filter(0, 0, 0, 5);
for(int I= 1; I< numbImgs; I++){
//aray[I].Copy(aray[0], 0, 0, sf::IntRect(0, 0, 0, 0), true);
aray[I] = aray[0]; // error doesn't occur when commented out
RecolorImage(aray[I], filter);
}
}
Image& Image::operator =(const Image& Other)
{
Image Temp(Other);
std::swap(myWidth, Temp.myWidth);
std::swap(myHeight, Temp.myHeight);
std::swap(myTextureWidth, Temp.myTextureWidth);
std::swap(myTextureHeight, Temp.myTextureHeight);
std::swap(myTexture, Temp.myTexture);
std::swap(myIsSmooth, Temp.myIsSmooth);
std::swap(myNeedArrayUpdate, Temp.myNeedArrayUpdate);
std::swap(myNeedTextureUpdate, Temp.myNeedTextureUpdate);
myPixels.swap(Temp.myPixels);
return *this;
}
void CreateTransition(sf::Image&start,sf::Image animationArray[numbImgs]){
animationArray[0]=开始;
void threadFunc(void*imgaray);
线程线程(threadFunc,reinterpret_cast(animationArray));
thread.Launch();
thread.Wait();//一旦代码正常工作,请将其注释掉
}
void threadFunc(void*ptr){
sf::Image*aray=重新解释铸件(ptr);
彩色滤光片(0,0,0,5);
对于(int I=1;I
以下几点可能有助于缩小原因:
- 当程序崩溃时,堆损坏很少发生,这使得它们很难被跟踪。它可能与崩溃点的对象相关,也可能是另一个对象/代码损坏了它
- 在
CreateTransition()
中,通过值传递animationaray[]
,然后将其传递到线程过程中。当您从CreateTransition()
返回时,animationaray[]
的生存期结束,这意味着如果线程过程在此点之后运行,其void*ptr
参数将不会指向有效对象。在当前代码中确实有一个thread.Wait()
,但也有一个关于删除它的注释。除非有特殊原因,否则通过引用传递animationaray[]
,或者为线程过程创建临时副本,以确保它在有效对象上运行
- 考虑使用
std::vector
而不是数组
- 确保理解并实现for
sf::image
和任何依赖类(如MyPixels
)。不这样做可能会导致双重释放、内存泄漏和堆损坏,正如您所看到的那样
- 如果所有其他方法都失败了,尝试在临时测试项目中复制该问题,并将其减少到尽可能少的代码量。一次删除一个
sf::image的成员,直到问题消失。类似地,删除CreateTransition()
中的行以及线程过程中的其他行。您要么以触发问题的一些非常具体的行结束,要么以一个空项目结束