views:

117

answers:

4

The following C++ program crashes on my Windows XP machine with a message "Abnormal program termination"

class Thing {};
int main()
{    
    for (;;) new Thing();    
}

I would say it's an out of memory problem, except I'm not sure Windows gets near the limit. Is it Windows killing it on purpose? If so, how does it decide?

A: 

Undoubtedly you are running out of VM.

John Dibling
It depends on the size of his swap file. With a sufficiently large swap (which is easy enough for a 32bit OS such as XP), you'll fill up your per-process address space before running out of memory.
R Samuel Klatchko
+1  A: 

Did you try to run it in debug?

In my case (Win7) it gave this error: This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

But in debug mode it showed that operator new threw excpetion bad_alloc which exactly mean out of memory.

Andrey
One of my least favorite error messages. If it's going to be meaningless to the user, shouldn't it at least offer a hint for the programmer?
David Thornley
programmer must catch possible exceptions
Andrey
+7  A: 

You're right it's an out-of-memory problem that causes your program to end. But it's not Windows that decides to end it with "Abnormal program termination". It's the C++ runtime ("msvcrt*.dll" on Windows) that raises the std::bad_alloc exception when new Thing fails to allocate memory.

You can verify that with a simple change:

#include <exception>
#include <iostream>
class Thing {};
int main()
{
    try
    {    
        for (;;) new Thing();    
    }
    catch(std::bad_alloc e)
    {
        std::cout << "ending with bad_alloc" << std::endl;
    }        
}

This will end the program normally when the program is out of memory. If you don't catch that exception, the unhandled exception will be handled by the C++ runtime, thus creating that famous "Abnormal program termination" message (or something similar).

AndiDog
Does cout's operator<< need to allocate memory? If you're out of memory and you again run out of memory in the catch block, won't you still get terminated? Since sizeof(Thing) is 1 I'd guess you'd be pretty close to capacity...
AshleysBrain
@AshleysBrain: I don't think that `std::cout <<` will allocate any memory. Maybe it needs some stack space, but that's reserved memory, so no more heap space needed IMO.
AndiDog
+2  A: 

It is the CRT that is killing your program. The required behavior for an unhandled exception (std::bad_alloc here) is a call to terminate(). Which displays the "Abnormal program termination" message in the MSVC implementation and calls abort() to kill the program.

Hans Passant