【问题标题】:heap corruption when deconstructing sf::Image array解构 sf::Image 数组时的堆损坏
【发布时间】:2011-10-30 06:14:39
【问题描述】:

所以我正在尝试为 SFML 中的 sf::Image 制作淡入淡出过渡动画,但我遇到了一个小问题。

当我不注释掉下面调用的函数时,当图像被解构时,我在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;
}

【问题讨论】:

    标签: c++ image pixel sfml


    【解决方案1】:

    一些可以帮助您缩小原因的事情:

    • 在程序崩溃时很少发生堆损坏,这使得它们难以追踪。它可能与崩溃点的对象有关,也可能是另一个损坏它的对象/代码。
    • 在CreateTransition() 中,您通过值传递animationArray[],然后将其传递给线程过程。 animationArray[] 的生命周期在您从 CreateTransition() 返回时结束,这意味着如果线程过程在此之后运行,其 void* ptr 参数将不会指向有效对象。您在当前代码中确实有 thread.Wait(),但也有关于删除它的评论。要么通过引用传递animationArray[],除非有特定原因不这样做,或者为线程过程创建一个临时副本以确保它在有效对象上运行。
    • 考虑使用std::vector&lt;sf::Image&gt; 而不是数组。
    • 确保您理解并实现Rule of Three 用于sf::image 和任何依赖类(如MyPixels)。不这样做可能会导致您看到的双重释放、内存泄漏和堆损坏。
    • 如果所有其他方法都失败,请尝试在临时测试项目中复制该问题并将其减少到尽可能少的代码量。一次删除一个sf::image 的成员,直到问题消失。同样,删除CreateTransition() 中的行和线程过程中的其他行。您最终会得到一些触发问题的非常具体的行或一个空项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-02
      • 2016-08-23
      • 2013-09-02
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多