My program is crashing only when it's compiled in optimized or default mode. It does not crash in debug mode. The cpu goes up to 100%, the memory increases real fast and the program crashes shortly after.
Here's what I'm developping on:
CentOS 5.3
Kernel 2.6.18-218.1.16.el5
KDevelop 3.3.4
GCC 4.1.2
I think I have narrowed down the problem to a specific function in the program. It's fairly simple here's the code:
bool MyClass::ReadData()
{
unsignedchar* buffer;
stringstream bufferStream;
int bytes_read;
try
{
// fileID is declared in a parent class and is assigned a value in a
// previous function
ioctl(fileID, FIONREAD, &bytes_read);
if (bytes_read > 0)
{
buffer = (unsignedchar*) malloc(bytes_read);
read(fileID, buffer, bytes_read);
// Get the numeric value of each byte in the buffer
for (int bufferIndex = 0; bufferIndex < bytes_read; bufferIndex++)
bufferStream << (int)buffer[bufferIndex] << ',';
// Convert bufferStream to a string;
// rawData is declared in a parent class;
rawData = bufferStream.str();
// Free the memory
free(buffer);
returntrue;
}
}
catch (exception& e)
{
ErrorHelper::LogError(e.what());
}
catch (...)
{
ErrorHelper::LogError("Unknown error");
}
returnfalse;
};
Here are some facts:
If I comment the rawData line it does not crash.
If I add a line ErrorHelper::LogError("anything") at the beginning of the function or right after the rawdata line it does not crash... what the hell?!?
Changing the CXXFLAGS -O2 option in the makefile to -O1 made the problem dissapear, but I don't know why. I know that -O2 means several more optimization flags are used by the compiler.
Leaving the makefile intact (with the -O2) and adding the following line of code at the end of my function(after free(buffer)) also made the problem dissapear:
bufferStream.str(""); // Clear buffer stream
Again I'm not sure if this is just a coincidence or not but it was recommended to me so it's probably not a bad thing to do.
I'd sure like to understand all of this so any help is welcome.