Marc.2377
Marc.2377

Reputation: 8734

Code won't execute unless cout is used

I wrote a very simple program to see how it would behave when allocating many objects in memory. It runs fine and will consume all of my computer's memory given enough time, unless the cout statement is removed. Without that line, the program will simply exit right after initialization. Why?

Code:

#include <iostream>

class Test
{
    long long test1[10];
    long long test2[10];
    long long test3[10];
    long long test4[10];
    long long test5[10];
};

int main()
{
    for (int i = 0; i <= 500000; ++i)
    {
        new Test;
        new Test;
        new Test;
        new Test;

        std::cout << i << "\n"; // Program won't work as desired without this
    }
    return 0;
}

Setup: Visual Studio 2013, Release, x64, Static Crt

Edit: I posted this question in a hurry when at work, sorry for being careless. Now it's right.

Upvotes: 1

Views: 113

Answers (1)

Drew Dormann
Drew Dormann

Reputation: 63839

Without the std::cout line and with optimizations turned on, your compiler is determining that there is a faster algorithm that's equivalent to the logic you wrote.

The faster algorithm is "do nothing".


Note: this is possible because your compiler is assuming that an "out of memory" scenario isn't a desired side-effect. So a faster algorithm is valid, even if it lowers the likelihood of running out of memory.

Upvotes: 3

Related Questions