stonebird
stonebird

Reputation: 339

c++ main() brain teaser

Can you think of a situation where your program would crash without reaching the breakpoint which you set at the beginning of main()?

My answer is during the initialization of static variables, but not sure...

Upvotes: 3

Views: 901

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361402

My answer gives 100% guarantee that this will crash before main().

#include <exception>

struct A
{
   A() 
   {
       std::terminate(); //from <exception>
       //you can also call std::abort() from <cstdlib>
   }
};
A a;

int main(){}

Demo : http://www.ideone.com/JIhcz


Another solution:

struct A
{
   A() 
   {
       throw "none";
   }
};
A a;

int main(){}

Demo : http://www.ideone.com/daaMe

Upvotes: 2

Christo
Christo

Reputation: 9075

THe above examples are true, but in my experience it's usually due to some problem loading a DLL...

Upvotes: 3

Prasoon Saurav
Prasoon Saurav

Reputation: 92864

A very simple example

struct abc
{
   abc()
   {
       int* p = 0;
       *p = 42; // Drat!
   }
};

abc obj;
int main(){}

Upvotes: 2

Related Questions