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

标签 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();
}

最佳答案

正如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();
}

关于qt - 尝试删除Qimage Format_RGB888时Qt应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63112846/

相关文章:

C++/Qt : Just a LNK2019 and I don't know why

带有 InnoDB 表的 MySQL 不断崩溃

释放包含滚动 UITableView 的 View Controller 时,iPhone 应用程序崩溃

Android 加载图像作为布局背景会导致应用程序崩溃

qt - QImage 到 QML

c++ - 加载 QPixmap 数据的更好方法

c++ - 我应该在 Qt 中尽可能多地使用信号/插槽吗?

c++ - Qt C++ QDomDocument,递归迭代 XML 数据,检索没有子数据的文本元素

c++ - 如何在 Qt 中调整图像大小以按比例缩放?

python - 如何在QT中创建带有文本和颜色的简单图像(QImage)并将其另存为文件