PDA

View Full Version : glibc detected main: malloc(): memory corruption: 0x0818f070*** on a simple program



fatecasino
7th December 2010, 04:16
why this part of code:


int rows = 3, cols = 2, temp, j;
double ** dataArray = new double* [rows];
for(int i = 0; i < rows; ++i)
dataArray[i] = new double(cols);

for (int i = 0; i < rows*cols; i++) {
temp =int(i/2);
j = i%2;
dataArray[temp][j] = temp*j;

}

gives me the following error in Qt???

&"warning: GDB: Failed to set controlling terminal: Invalid argument\n"
*** glibc detected *** /home/tgf/qtExamples/cpp/main6-build-desktop/main6: malloc(): memory corruption: 0x0818f070 ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6(+0x6b591)[0xfe7591]
/lib/tls/i686/cmov/libc.so.6(+0x6e395)[0xfea395]
/lib/tls/i686/cmov/libc.so.6(__libc_malloc+0x5c)[0xfebf9c]
/usr/lib/libstdc++.so.6(_Znwj+0x27)[0xefec07]
/usr/lib/libQtGui.so.4(+0x6ccc8d)[0x7fac8d
........ (lots of error lines like the above)

I tried this part of code in Geany and it worked normally.

ChrisW67
7th December 2010, 04:44
This has nothing to do with Qt. This is a C++ question.

Line 4 is allocating a single double with the value cols, not doing what you think it is doing, i.e. allocating an array of cols doubles. Consequently you end up writing outside the bounds of the allocated memory. This will probably also cause issue when you try to delete[] the memory.

fatecasino
7th December 2010, 16:13
thanks so much!
I was struggling for 5+ hours to solve this and I couldn't see the obvious


dataArray[i] = new double(cols);


I just wanted to create a 2d array of doubles (dynamic allocation of memory) and what happened is this (using Creator):
when i typed "double" the editor automatically typed () thinking that it is a kind of a function. I didn't notice it, and after that, my eyes always were seeing () as [] !!!!

dataArray[i] = new double[cols];

That's (and much more) what happens after continuous hours of coding. The strange bit is that Geany was not complaining at all and I thought it was a Qt thing.