Tom Peety
Tom Peety

Reputation: 5

Why does g++ make my code execute in a different order than written and how do I disable this "optimization"?

For example:

#include <stdio.h>
#include <string>
int main() {
    std::string* stuff(NULL);

    printf("allocating memory..."); //line 2

    stuff = new std::string[500000000]; //line 3

    delete [] stuff; //line 4

    return 0;
}

when executed runs line 3 (and possibly line 4) before line 2. Now I know this is probably some good optimization feature but sometimes the right order is needed.

Upvotes: 0

Views: 270

Answers (3)

Pietro Lorefice
Pietro Lorefice

Reputation: 1487

The problem is here:

printf("allocating memory..."); //line 2

In many architectures you have buffered output, which means that what you print on the screen is not shown immediately but stored in a memory buffer. To flush the buffer and ensure that he is printed immediately, you can use

printf("allocating memory...\n"); //line 2 with the \n character that flushes the buffer

although I didn't find anything to prove this besides personal experience, or alternatively, if you don't want to go to a new line (and be absolutely sure of flushing) you can use fflush(stdout) right after line 2.

Upvotes: 10

bobah
bobah

Reputation: 18864

-O0 flag disables all optimizations in GCC.

But the effect you are observing is most probably not due to an optimization but rather a result of file IO buffering.

Inserting fflush(stdout) just after printf(...) will make IO system flush the buffer which in case of logging to a file should give you the right order of events (assuming you are logging malloc() calls to the same file and this is where you observe out of order events).

Upvotes: 3

leftaroundabout
leftaroundabout

Reputation: 120751

In C++, you might want to write it like this:

#include <iostream>
#include <string>
int main() {
    std::string* stuff(NULL);

    std::cout << "allocating memory..."; //line 2
    std::cout.flush();   // ensures the buffer is actually written to the terminal right here

    stuff = new std::string[500000000]; //line 3

    delete [] stuff; //line 4

    return 0;
}

Upvotes: 3

Related Questions