2
#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();
}

When I run the above code, about 1 out of 5 times I get the following error:

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...

This is driving me crazy, since the error shows up totally randomly.

The whole crash log is at http://pastebin.com/Qtp9T2gW

Tarandeep Gill
  • 1,506
  • 18
  • 34

2 Answers2

5

The line:

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

Is totally different to:

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

You also need to combine operator new[] with operator delete[], and operator new with operator delete - you can't mix and match the different combinations.

Darren Engwirda
  • 6,915
  • 4
  • 26
  • 42
  • Yea, thats exactly what was wrong! I am coming back to C++ after working in PHP/JavaScript for many many years! Thanks buddy :) – Tarandeep Gill Feb 09 '12 at 01:12
2

You probably meant to say

char* aa = new char[25];

To create an array of 25 chars.

EboMike
  • 76,846
  • 14
  • 164
  • 167