Program crashing in optimized or default mode

Hi,

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
bool MyClass::ReadData()
{
    unsigned char* 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 = (unsigned char*) 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);
            
            return true;
        }
    }
    catch (exception& e)
    {
        ErrorHelper::LogError(e.what());
    }
    catch (...)
    {      
        ErrorHelper::LogError("Unknown error");
    }

    return false;
};


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?!?

Any clue because I'm clueless at this point.

Thanks.

Olivier
How was rawData declared?
string rawData;
New facts:

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.
Last edited on
Topic archived. No new replies allowed.