【问题标题】:Totally random malloc errors in Qt App on Mac OSXMac OSX 上 Qt App 中的完全随机 malloc 错误
【发布时间】:2012-02-09 00:59:42
【问题描述】:
#include <QtCore/QCoreApplication>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    a.setApplicationName("xxx");
    char bb[25] = {10, 1, 64, 18, 20, 116, 97, 114, 97, 110, 103, 105, 108, 108, 51, 64, 103, 109, 97, 105, 108, 46, 99, 111, 109};
    char* aa = new char(25);
    memcpy(aa, bb, 25);
    delete aa;
    return a.exec();
}

当我运行上面的代码时,大约五分之一的时候我得到以下错误:

tftest(28702,0x7fff70de3cc0) malloc: *** error for object 0x10160ee28: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Press <RETURN> to close this window...

这让我发疯,因为错误完全随机出现。

整个崩溃日志位于http://pastebin.com/Qtp9T2gW

【问题讨论】:

    标签: c++ macos qt malloc


    【解决方案1】:

    行:

    char *aa = new char(25); // dynamically allocate a single char = 25
    

    完全不同于:

    char *aa = new char[25]; // dynamically allocate an array [0..24] of char
    

    您还需要将operator new[]operator delete[] 组合,并将operator newoperator delete 组合在一起 - 您不能混合和匹配不同的组合。

    【讨论】:

    • 是的,这正是问题所在!在 PHP/JavaScript 工作多年后,我又回到了 C++!谢谢哥们:)
    【解决方案2】:

    你可能是想说

    char* aa = new char[25];
    

    创建一个包含 25 个字符的数组。

    【讨论】:

      猜你喜欢
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      相关资源
      最近更新 更多