尝试删除Qimage Format_RGB888时Qt应用程序崩溃

时间:2020-07-27 09:55:15

标签: qt crash qimage heap-corruption

我得到一个“检测到堆损坏:在正常块之后……CRT检测到应用程序在堆缓冲区结束后写入了内存。” 当变量test被销毁时。 如果更改图像大小,则不会发生崩溃,我认为这与内存对齐有关,但我无法弄清楚。

我正在使用MSVC 2017 64位版的官方Qt版本

#include <QCoreApplication>
#include <QImage>

QImage foo(int width, int height)
{
    QImage retVal(width, height, QImage::Format_RGB888);
    for (int i = 0; i < height; ++i) // read each line of the image
    {
        QRgb *lineBuf = reinterpret_cast<QRgb *>(retVal.scanLine(i));
        for (int j = 0; j < width; ++j)
        {
            lineBuf[j] = qRgb(0,0,0);
        }
    }
    return retVal;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    {
        QImage test = foo(5,5);
    }
    return a.exec();
}

1 个答案:

答案 0 :(得分:0)

正如GM在上述评论中所建议的那样,问题在于QRgb是32位结构。 我已经更改了用自定义RGB结构替换QRgb的代码

struct RGB {
   uint8_t r;
   uint8_t g;
   uint8_t b;
};

QImage foo(int width, int height)
{
    QImage retVal(width, height, QImage::Format_RGB888);
    for (int i = 0; i < height; ++i) // read each line of the image
    {
        RGB *lineBuf = reinterpret_cast<RGB *>(retVal.scanLine(i));
        for (int j = 0; j < width; ++j)
        {
            RGB tmp;
            //.... do stuff with tmp
            lineBuf[j] = tmp;
        }
    }
    return retVal;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    {
        QImage test = foo(5,5);
    }
    return a.exec();
}
相关问题