346

I'm trying to make a Python program that interfaces with a different crashy process (that's out of my hands). Unfortunately the program I'm interfacing with doesn't even crash reliably! So I want to make a quick C++ program that crashes on purpose but I don't actually know the best and shortest way to do that, does anyone know what to put between my:

int main() {
    crashyCodeGoesHere();
}

to make my C++ program crash reliably

Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
jonathan topf
  • 7,897
  • 17
  • 55
  • 85
  • 6
    you can use inline assembly to attempt to execute privleged instructions: `asm { cli; };` – Nate Koppenhaver Dec 13 '11 at 18:19
  • @aitchnyu I think there is a difference in the usability of the answers to each question. (FYI: I've not voted anything for either question) – Andrew Barber Dec 13 '11 at 20:36
  • any comment of throwing exception while one already propogates?? plz chk my answer below anc comment – Abhinav Dec 20 '11 at 17:38
  • 5
    Redis uses the following `*((char*)-1) = 'x';` code to induce a crash in order to debug read more in my [answer here](http://stackoverflow.com/a/20844979/1708801) – Shafik Yaghmour Dec 16 '14 at 14:45
  • I found this question searching for a test case for a crash reporting system. I needed to force a crash during normal runtime to invoke the crash reporter and stack dump sending. Thanks! – Cory Trese Oct 07 '16 at 15:14
  • This should always crash on all systems. `int *p = (int *)-1; *p = 1;`. This is because memory address 2^64 - 1 does not exist on any system, at least, not now (assuming pointer is 8 bytes long). –  Feb 24 '22 at 08:06

31 Answers31

293

The abort() function is probably your best bet. It's part of the C standard library, and is defined as "causing abnormal program termination" (e.g, a fatal error or crash).

  • 14
    Note that a crash through `abort()` doesn't call any destructors or `atexit` functions, though that will likely not matter here. – Xeo Dec 12 '11 at 23:02
  • 155
    @Xeo: If it did call destructors and `atexit`s, it wouldn't be a crash now would it? – Donal Fellows Dec 13 '11 at 18:00
  • Since `abort()` is the correct answer, then should 'exit(-1);` be acceptable? – asir6 Dec 19 '11 at 07:51
  • 10
    No, since it doesn't cause a crash, merely reports something couldn't be done. – boatcoder Jul 02 '12 at 03:29
  • Windows. GCC-5.4.0. Exit code: 3. No error message box. Console message: "This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.". – Vadzim Jul 03 '18 at 15:01
  • Will calling `abort()` trigger things like crashpad? My reason for wanting to crash my application is to ensure that crash-reporting is working correctly. – Ben Feb 17 '22 at 15:09
127

Try:

raise(SIGSEGV);  // simulates a standard crash when access invalid memory
                 // ie anything that can go wrong with pointers.

Found in:

#include <signal.h>
Martin York
  • 257,169
  • 86
  • 333
  • 562
  • 3
    It's more than just implementation-defined -- the signal can be caught with `signal()`. Most sane applications don't, though. –  Dec 12 '11 at 22:56
  • 13
    It will crash in exactly the same way as a normal SIGSEGV within the application (which is the way most applications crash). It is well defined what it does (by default it exits the application and generates a core file). Yes you can set a handler, but if you have one don't you want to test that in the same way!! – Martin York Dec 13 '11 at 04:11
  • 2
    +1 for `raise()`. This lets you test for a ton of different types of exceptions by just changing the argument. –  Dec 13 '11 at 05:06
  • 3
    favorite solution, however it is platform dependent . – Nadim Farhat Feb 05 '14 at 13:50
  • @NadimFarhat: In what way. A signal is a signal on all platforms. – Martin York Feb 05 '14 at 23:46
  • Windows. GCC-5.4.0. Exit code: 3. No error message box. No console message. – Vadzim Jul 03 '18 at 15:01
76

Dividing by zero will crash the application:

int main()
{
    return 1 / 0;
}
Vadzim
  • 24,954
  • 11
  • 143
  • 151
Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94
  • 33
    Depending on how clever your compiler is this will be caught at compile time. I know that visual studio 2008 won't compile this for c++ or c#. – AidanO Jan 03 '12 at 16:05
  • Since this code is subject to constant folding it will not be even be compiled successfully so we cannot here say it can crash anything since you'll not have executable to run. – Artur Apr 04 '12 at 14:31
  • 2
    I've compiled and run it, do you want me to sand you the .exe ? – Roee Gavirel Apr 04 '12 at 14:32
  • 1
    In release configuration in Visual Studio recent versions like 2010, it will run without problem. I guess it's some optimization. – tedyyu Sep 13 '13 at 07:54
  • 2
    iirc it does not crashes on arm – sherpya Mar 30 '15 at 17:04
  • 3
    This is undefined behavior and is not guaranteed to crash. Often compilers assume undefined behavior to be unreachable. This can lead to the body of `main` being entirely deleted including the `ret` instruction. Execution might just fall into the following function. – usr Sep 27 '16 at 18:39
  • My compiler didn't allow 1/0, I had to do this: int x=0; 1/x; – Jesus H Oct 24 '16 at 18:31
  • Windows. GCC-5.4.0. Exit code: -1073741676. No console message. Pops up error message box: "Application Error. The exception Integer division by zero. (0x0000094) occurred in the application at location 0x001a3fe2. Click on OK to terminate the program." – Vadzim Jul 03 '18 at 14:59
  • Dividing by 0 is UB... it MIGHT crash the application. It might also just return 5. – UKMonkey Jul 19 '19 at 11:41
  • Tested on Visual Studio 2013: it generates error at compiling time: error C2124: divide or mod by zero – Gustavo Rodríguez Mar 18 '22 at 15:03
70
*((unsigned int*)0) = 0xDEAD;
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
  • 57
    This is not guaranteed to crash. – Windows programmer Dec 13 '11 at 04:55
  • 8
    @Windowsprogrammer: no, it's not *guaranteed*. But which sane OS *doesn't* stop an application that tries to access memory at address 0? – Joachim Sauer Dec 13 '11 at 06:55
  • 33
    "But which sane OS doesn't stop an application that tries to access memory at address 0?" -- That isn't really what you want to ask, but I'll answer anyway. In some computers there is RAM at address 0, and it is perfectly meaningful for a program to store a value there. A more meaningful question would be "Which OS doesn't stop an application that access memory at the address that a C++ implementation reserved for a null pointer?" In that case I don't know of any. But the original program is about the C++ language not about OSes. – Windows programmer Dec 13 '11 at 07:41
  • 6
    Its undefined behavior. It is perfectly OK for this to do nothing. A machine that will not crash: Anything running a Z80 series processor (I assume (my Z80a does nothing)). – Martin York Dec 13 '11 at 09:10
  • 29
    Although this isn't *guaranteed* to crash, it is one of the most common *kinds* of crash in C++. So if you want to simulate a crash, this is an "authentic" way to do it :) – Chris Burt-Brown Dec 13 '11 at 10:03
  • 1
    @ChrisBurt-Brown: Accessing the zero address on machines that will actually crash generates a SIGSEGV signal. So much easier to just just raise(SIGSEGV). Thus you simulate the exact behavior in a way that is reproducible. – Martin York Dec 13 '11 at 16:23
  • 3
    @Loki: You run python on your Z80-based system? I'm impressed; I didn't think you could address enough memory on an 8-bit system to do that… – Donal Fellows Dec 13 '11 at 18:04
  • @DonalFellows: No. What made you think python? – Martin York Dec 13 '11 at 19:21
  • @Loki, python is in the original question up the top. given its running python, its likely to be running on a system with a MMU and if so, its most probable this will crash all the time. – Keith Nicholas Dec 13 '11 at 20:44
  • 5
    @KeithNicholas: My original point holds. I just came up with one system off the top of my head. Assuming it will crash is a bad idea as what may crash on your PC does not mean it holds any further than that. A lot of people got hurt by assuming PC was the predominant architecture. There has been a huge shift in development recently and a lot of development has moved to mobile devices were there some assumptions no longer held. Who knows what/when the next architecture change will do. Relying on (or getting used to) undefined behavior working a particular way will just lead to bad things later. – Martin York Dec 13 '11 at 20:59
  • 3
    @Loki, I think within the context of the question asked, this is ok. The guy just wants a temporary method of crashing to bootstrap his python testing code. This method is a common *real* crash that C++ systems do. Other than abort, which is a non 'real' crash, there is no defined way of crashing, as almost by definitions, crashes are happen when you cross into the land of undefined behaviour. – Keith Nicholas Dec 13 '11 at 21:23
  • 4
    @Keith Nichola: I disagree. This question is going to be read by lots more people than the OP trying to work out how to cause a crash. We need to answer this taking these people into consideration. – Martin York Dec 14 '11 at 03:27
  • 4
    @JoachimSauer: Mac OS Classic would be one such OS (Mac OS X, of course, does stop the program). – derobert Dec 14 '11 at 11:10
  • 4
    @JoachimSauer: HPUX allows reads and writes to 0. And it's a recent enough OS that there are still people running it. – Sean McMillan Dec 14 '11 at 15:33
  • This will not compile if your compiler warning flags are overly zealous, and you sometimes don't have the power to change them. – P Shved Mar 13 '13 at 23:48
  • 2
    That's UB. It doesn't depend on architecture only, the compiler can assume this code is never reached. `echo 'void crash(void) { *(unsigned *)0 = 0xdead; }' | clang -std=c99 -O2 -c -x c -` gives `:1:20: warning: indirection of non-volatile null pointer will be deleted, not trap [-Wnull-dereference]` and suggests using either `__builtin_trap` or `*(volatile unsigned *)0`. – mafso Nov 06 '14 at 22:17
  • This is undefined behavior and is not guaranteed to crash. Often compilers assume undefined behavior to be unreachable. In that case at least this line is going to be deleted and other code might as well be. – usr Sep 27 '16 at 18:41
  • @JoachimSauer: Win95/98 lets user-space write the zero page (https://news.ycombinator.com/item?id=13263976), where the IDT (interrupt descriptor table) resides. Oh nvm, you said "sane", not "once widely used". – Peter Cordes Jul 23 '18 at 12:37
  • Many, many microcontrollers have data at location 0 that you are meant to write. – Jerry Jeremiah Oct 29 '20 at 21:04
56

Well, are we on stackoverflow, or not?

for (long long int i = 0; ++i; (&i)[i] = i);

(Not guaranteed to crash by any standards, but neither are any of the suggested answers including the accepted one since SIGABRT could have been caught anyway. In practice, this will crash everywhere.)

sam hocevar
  • 11,853
  • 5
  • 49
  • 68
36
 throw 42;

Just the answer... :)

Macke
  • 24,812
  • 7
  • 82
  • 118
  • 1
    Windows. GCC-5.4.0. Exit code: 3. No error message box. Console message: "terminate called after throwing an instance of 'int' This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.". – Vadzim Jul 03 '18 at 15:02
17

assert(false); is pretty good too.

According to ISO/IEC 9899:1999 it is guaranteed to crash when NDEBUG is not defined:

If NDEBUG is defined [...] the assert macro is defined simply as

#define assert(ignore) ((void)0)

The assert macro is redefined according to the current state of NDEBUG each time that is included.

[...]

The assert macro puts diagnostic tests into programs; [...] if expression (which shall have a scalar type) is false [...]. It then calls the abort function.

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
Dan F
  • 17,654
  • 5
  • 72
  • 110
12

Since a crash is a symptom of invoking undefined behaviour, and since invoking undefined behaviour can lead to anything, including a crash, I don't think you want to really crash your program, but just have it drop into a debugger. The most portable way to do so is probably abort().

While raise(SIGABRT) has the same effect, it is certainly more to write. Both ways however can be intercepted by installing a signal handler for SIGABRT. So depending on your situation, you might want/need to raise another signal. SIGFPE, SIGILL, SIGINT, SIGTERM or SIGSEGV might be the way to go, but they all can be intercepted.

When you can be unportable, your choices might be even broader, like using SIGBUS on linux.

PlasmaHH
  • 15,673
  • 5
  • 44
  • 57
  • 1
    I really doubt that he wants a debugger involved. He seems to want to test what happens when the caller of a crashing program gets a crash sent his way. Which is very reasonable. – Donal Fellows Dec 13 '11 at 18:03
10

The answer is platform specific and depends on your goals. But here's the Mozilla Javascript crash function, which I think illustrates a lot of the challenges to making this work:

static JS_NEVER_INLINE void
CrashInJS()
{
    /*
     * We write 123 here so that the machine code for this function is
     * unique. Otherwise the linker, trying to be smart, might use the
     * same code for CrashInJS and for some other function. That
     * messes up the signature in minidumps.
     */

#if defined(WIN32)
    /*
     * We used to call DebugBreak() on Windows, but amazingly, it causes
     * the MSVS 2010 debugger not to be able to recover a call stack.
     */
    *((int *) NULL) = 123;
    exit(3);
#elif defined(__APPLE__)
    /*
     * On Mac OS X, Breakpad ignores signals. Only real Mach exceptions are
     * trapped.
     */
    *((int *) NULL) = 123;  /* To continue from here in GDB: "return" then "continue". */
    raise(SIGABRT);  /* In case above statement gets nixed by the optimizer. */
#else
    raise(SIGABRT);  /* To continue from here in GDB: "signal 0". */
#endif
}
Paul Biggar
  • 27,579
  • 21
  • 99
  • 152
  • 3
    You should totally drop that and use jQuery instead. – Thomas Weller Jul 26 '16 at 21:01
  • 1
    This is undefined behavior and is not guaranteed to crash. Often compilers assume undefined behavior to be unreachable. In that case at least the crashing line is going to be deleted and other code might be as well. – usr Sep 27 '16 at 18:44
9

The only flash I had is abort() function:

It aborts the process with an abnormal program termination.It generates the SIGABRT signal, which by default causes the program to terminate returning an unsuccessful termination error code to the host environment.The program is terminated without executing destructors for objects of automatic or static storage duration, and without calling any atexit( which is called by exit() before the program terminates)function. It never returns to its caller.

samridhi
  • 500
  • 2
  • 10
9

I see there are many answers posted here that will fall into lucky cases to get the job done, but none of them are 100% deterministic to crash. Some will crash on one hardware and OS, the others would not. However, there is a standard way as per official C++ standard to make it crash.

Quoting from C++ Standard ISO/IEC 14882 §15.1-7:

If the exception handling mechanism, after completing the initialization of the exception object but before the activation of a handler for the exception, calls a function that exits via an exception, std::terminate is called (15.5.1).

struct C {
    C() { }
    C(const C&) {
        if (std::uncaught_exceptions()) {
            throw 0; // throw during copy to handler’s exception-declaration object (15.3)
        }
    }
};
int main() {
    try {
    throw C(); // calls std::terminate() if construction of the handler’s
    // exception-declaration object is not elided (12.8)
    } catch(C) { }
}

I have written a small code to demonstrate this and can be found and tried on Ideone here.

class MyClass{
    public:
    ~MyClass() throw(int) { throw 0;}
};

int main() {
  try {
    MyClass myobj; // its destructor will cause an exception

    // This is another exception along with exception due to destructor of myobj and will cause app to terminate
     throw 1;      // It could be some function call which can result in exception.
  }
  catch(...)
  {
    std::cout<<"Exception catched"<<endl;
  }
  return 0;
}

ISO/IEC 14882 §15.1/9 mentions throw without try block resulting in implicit call to abort:

If no exception is presently being handled, executing a throw-expression with no operand calls std::terminate()

Others include : throw from destructor: ISO/IEC 14882 §15.2/3

Abhinav
  • 1,496
  • 3
  • 15
  • 31
  • **[`std::terminate()`](https://en.cppreference.com/w/cpp/error/terminate)** works for me in a C++ application (so +1) but it might not be so simple if the application *does* have a non-default `std::terminate_handler` installed. The default one raises [`std::abort`](https://en.cppreference.com/w/cpp/utility/program/abort) which *can* be handled and it isn't clear to me what will happen for a Windoze PC system then... – SlySven Sep 15 '20 at 22:42
8
*( ( char* ) NULL ) = 0;

This will produce a segmentation fault.

wrren
  • 1,281
  • 9
  • 11
  • 10
    This is not guaranteed to crash. – Windows programmer Dec 13 '11 at 04:55
  • 23
    "What will happen instead?" -- Anything could happen instead. Behaviour is undefined, so the implementation could assign 0 to one of your program's variables, or it could assign 42 to one of your program's variables, or it could format your hard drive and continue executing your program. – Windows programmer Dec 13 '11 at 07:38
  • 7
    (continuing "Windows programmer" set of mind) It can make you computer explode, or it may cause it to come a live and take over the humanity. or... it will crash in 99.9% and it's defined as "undefined behavior" because no one wants to take responsibility on it. – Roee Gavirel Dec 14 '11 at 06:38
  • 1
    Actually, that's not guaranteed to even do undefined behaviour - it could completely defined and work properly. Consider this code: http://pastebin.com/WXCtTiDD (Tested on Linux as root, you could do this as a non-root user too if you do some config changes http://wiki.debian.org/mmap_min_addr) – cha0site Jun 14 '12 at 18:35
  • 2
    @cha0site: It is guaranteed to be undefined behavior by the Standard, because that is dereferencing a null pointer. Whatever behavior you observed on Linux is allowable under the umbrella of "undefined behavior" – Ben Voigt May 12 '13 at 07:28
  • Different platforms can have different bahavior – Abhinav Jul 30 '14 at 16:56
  • 1
    This is undefined behavior and is not guaranteed to crash. Often compilers assume undefined behavior to be unreachable. In that case at least the crashing line is going to be deleted and other code might be as well. – usr Sep 27 '16 at 18:44
  • It didn't crash on Irix. I sadly realized when we ported that code to Linux (where we even didn't reach `main()`). – Scheff's Cat Nov 29 '19 at 09:57
  • Lots of microcontrollers have data at location 0 that you are meant to write. Even the 6502 falls into this category. – Jerry Jeremiah Oct 29 '20 at 21:10
7

This crashes on my Linux system, because string literals are stored in read only memory:

0[""]--;

By the way, g++ refuses to compile this. Compilers are getting smarter and smarter :)

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
7

This one is missing:

int main = 42;
mvds
  • 45,755
  • 8
  • 102
  • 111
6

What about stack overflow by a dead loop recursive method call?

#include <windows.h>
#include <stdio.h>

void main()
{
    StackOverflow(0);
}

void StackOverflow(int depth)
{
    char blockdata[10000];
    printf("Overflow: %d\n", depth);
    StackOverflow(depth+1);
}

See Original example on Microsoft KB

sll
  • 61,540
  • 22
  • 104
  • 156
  • 4
    What would prevent a Sufficiently Smart Compiler from optimizing away both the unused stack allocation and the tail call? – JB. Dec 14 '11 at 14:47
  • @JB: unfortunatly have no idea because not familar with existing compilers optimization logic – sll Dec 14 '11 at 15:43
  • 8
    Well, compiled here with gcc 4.6.0 at optimization levels -O2 and above, it optimizes just fine. It needs -O1 or lower to segfault. – JB. Dec 14 '11 at 16:06
  • @Abhinav: Just post your answer with all of these ways expressed as an examples in C++ :) – sll May 23 '13 at 09:20
4

This is the snippet provided by Google in Breakpad.

  volatile int* a = reinterpret_cast<volatile int*>(NULL);
  *a = 1;
Cory Trese
  • 1,148
  • 10
  • 23
  • 1
    Since I'm testing Breakpad this is exactly what I wanted! I found that some Breakpad minidumps don't produce a stack trace that points to the line in my code causing the crash. This one does, so I can use it as good p.o.c. test. – BuvinJ Feb 21 '18 at 14:48
4

This is a more guaranteed version of abort presented in above answers.It takes care of the situation when sigabrt is blocked.You can infact use any signal instead of abort that has the default action of crashing the program.

#include<stdio.h>
#include<signal.h>
#include<unistd.h> 
#include<stdlib.h>
int main()
{
    sigset_t act;
    sigemptyset(&act);
    sigfillset(&act);
    sigprocmask(SIG_UNBLOCK,&act,NULL);
    abort();
}
sll
  • 61,540
  • 22
  • 104
  • 156
bashrc
  • 4,725
  • 1
  • 22
  • 49
3

Although this question already has an accepted answer...

void main(){
    throw 1;
}

Or... void main(){throw 1;}

noɥʇʎԀʎzɐɹƆ
  • 9,967
  • 2
  • 50
  • 67
3
int i = 1 / 0;

Your compiler will probably warn you about this, but it compiles just fine under GCC 4.4.3 This will probably cause a SIGFPE (floating-point exception), which perhaps is not as likely in a real application as SIGSEGV (memory segmentation violation) as the other answers cause, but it's still a crash. In my opinion, this is much more readable.

Another way, if we're going to cheat and use signal.h, is:

#include <signal.h>
int main() {
    raise(SIGKILL);
}

This is guaranteed to kill the subprocess, to contrast with SIGSEGV.

  • 2
    This is not guaranteed to crash. – Windows programmer Dec 13 '11 at 04:57
  • 11
    The C++ language does not guarantee that 1 / 0 will cause a SIGFPE. Behaviour is undefined. The implementation could say the result is 42. – Windows programmer Dec 13 '11 at 05:09
  • Would this be a correct implementation? 42 is a well-defined number, it is not undefined. – Giorgio Dec 13 '11 at 06:36
  • Isn't that an integer division? Why should that result in a *floating-point* exception? – Joachim Sauer Dec 13 '11 at 06:56
  • 1
    When behaviour is undefined, the implementation can do whatever it wants. The C++ language neither prevents nor requires an implementation to write a crash dump, the C++ language neither prevents nor requires an implementation to assign 42, etc. – Windows programmer Dec 13 '11 at 07:43
  • In my personal opinion SIGFPE is not the appropriate choice for division by zero, and it wasn't the best choice on a 16-bit machine where dividing -32768 by -1 didn't fit in a 16-bit signed int. Intel didn't agree with me and a bunch of compiler developers don't agree with me. Anyway, since behaviour is undefined, SIGFPE is equally allowable as assigning 42 or formatting hard drives. – Windows programmer Dec 13 '11 at 07:46
  • 1
    @Windows programmer: The point is what undefined means. If I have a partial function f : A -> B, and f(a) is undefined for some a in A, then computing f(a) cannot return a value in B: either f(a) does not terminate or it returns some special value outside of B. Returning some random value b in B makes f(a) defined by f(a) = b, i.e. does not compute f as it was specified (f(a) MUST be undefined). So computing 1 / 0 cannot return a number because 1 / 0 is undefined on both integer and real numbers. IMO using undefined behaviour (i.e. anything will do) is not the correct approach here. – Giorgio Dec 13 '11 at 09:21
  • 1
    I think the correct approach to undefined is to either throw an exception or return a special value that indicates undefined (see e.g. the Maybe monad in Haskell). See also http://en.wikipedia.org/wiki/Monad_%28functional_programming%29#An_introductory_example_as_a_control_structure, http://en.wikipedia.org/wiki/Partial_functions – Giorgio Dec 13 '11 at 09:27
  • @Giorgio - the standard defines what the correct approach to handling things like this is and it's pretty clear - it's undefined behaviour, anything goes. – Flexo Dec 13 '11 at 09:34
  • @awoodland: I am afraid you are correct. I can only hope that the C++ specification will be fixed with the next C++ revision. – Giorgio Dec 13 '11 at 09:42
  • @Giorgio - the C++ specification was written to be as flexible as possible. *Implementations* may therefore choose to throw an exception or set a flag to indicate invalid number. The standard deliberately avoids specifying what that should be though in order to avoid imposing large burdens on platforms which would, for example, have to wrap *every* division in order to do this. – Flexo Dec 13 '11 at 09:47
  • @awoodland: Is checking if the second argument of x / y is zero a large burden? As far as I know checking if a register contains zero is one of the cheapest operations for a processor. – Giorgio Dec 13 '11 at 09:54
  • 2
    @Giorgio if the hardware doesn't have some way of trapping it automatically you still force compilers to emit at least two instructions, one of which would be a branch too. That's approximately doubling the cost of a division. Everybody pays that cost like that. If it's optional and you want it you can always use a library function for it still. If it's not optional and you don't want it you'd still end up paying the cost. – Flexo Dec 13 '11 at 10:09
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/5805/discussion-between-giorgio-and-awoodland) – Giorgio Dec 13 '11 at 10:35
  • For anyone googling later, Wikipedia informs me that SIGFPE is raised for backwards compatibility. AFAIK, there is no 'appropriate' signal for division by zero on POSIX platforms - `SIGFPE` is probably the closest. If one uses `signal()` calls properly - that is, setting a hander immediately before code that might cause a signal, and then resetting the signal handler to `SIG_DFL` immediately after those statements execute - the signal type isn't too important. If you're working with integers and you get a SIGFPE, it's pretty obvious what happened. –  Dec 13 '11 at 15:42
  • @AlexWebr: Please do not quote wikipedia as an authoritative source. Sure it is good for looking things up but follow the reference to the real source. Even wikipedia says do not use them as an authoritative source. – Martin York Dec 17 '11 at 06:40
  • 2
    @Giorgio: I have an application that does a 100,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 * 10^1000000 divisions. I know for a fact that 0 of these will be a division by zero though there is no way the compiler can know this. **I definitely do not want** the compiler to plant the check for a division by zero. – Martin York Dec 17 '11 at 06:44
  • @Loki Astari: if this creates a real performance problem you could perform your divisions using inline assembly. Furthermore, the compiler would only need to plant this check on a processor that does not trap division by zero itself which, to my knowledge, is quite rare. Anyway, I understand the C++ policy of not checking division by zero, pointers, array indices for performance reasons. – Giorgio Dec 17 '11 at 09:32
  • @Giorgio: Why should I pay for the cost just because you need/want it. Better to have no check and when I need it I will explicitly plant the check. The language designers made a choice. They opted for no checking so that we could have optimal speed as the default (Hence the operator[] and at()) The other choice would be to slow the code for everybody just so the incompetent/learners developers did so safely. I think they made the correct choice. I can write good safe/fast code without automated checks, I will explicitly add the checks when I need them thus only slowing my code when necessary. – Martin York Dec 17 '11 at 18:32
  • This is undefined behavior and is not guaranteed to crash. Often compilers assume undefined behavior to be unreachable. In that case at least the crashing line is going to be deleted and other code might be as well. – usr Sep 27 '16 at 18:45
3
int* p=0;
*p=0;

This should crash too. On Windows it crashes with AccessViolation and it should do the same on all OS-es I guess.

sll
  • 61,540
  • 22
  • 104
  • 156
laci37
  • 510
  • 4
  • 17
  • 5
    `on all OS-es` No, it doesn't crash in non protected OS (e.g. MS-DOS.) Actually, sometimes there *is* something in address 0! For x86 real mode, Interrupt Vector Table is in address 0. – ikh Aug 14 '14 at 10:28
  • It didn't crash on Irix. I sadly realized when we ported that code to Linux (where we even didn't reach `main()`. – Scheff's Cat Nov 29 '19 at 09:56
  • Lots of microcontrollers have data at location 0 that you are meant to write. Even the 6502 falls into this category. – Jerry Jeremiah Oct 29 '20 at 21:12
2
int main(int argc, char *argv[])
{
    char *buf=NULL;buf[0]=0;
    return 0;
}
Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
2

Writing to a read-only memory will cause segmentation fault unless your system don't support read-only memory blocks.

int main() {
    (int&)main = 0;
}

I have tested it with MingGW 5.3.0 on Windows 7 and GCC on Linux Mint. I suppose that other compilers and systems will give a similar effect.

Piotr Siupa
  • 3,929
  • 2
  • 29
  • 65
1

Or another way since we're on the band wagon.

A lovely piece of infinite recursion. Guaranteed to blow your stack.

int main(int argv, char* argc)
{
   return main(argv, argc)
}

Prints out:

Segmentation fault (core dumped)

hookenz
  • 36,432
  • 45
  • 177
  • 286
  • 13
    Calling `main` yourself is actually undefined behavior, in case you didn't know :) Also, tail recursion is *not* guaranteed to blow your stack. If you want a "guarantee", you have to do *something* after the recursive call, otherwise the compiler could optimize the recursion into an infinite loop. – fredoverflow Sep 27 '12 at 05:53
0
void main()
{

  int *aNumber = (int*) malloc(sizeof(int));
  int j = 10;
  for(int i = 2; i <= j; ++i)
  {
      aNumber = (int*) realloc(aNumber, sizeof(int) * i);
      j += 10;
  }

}

Hope this crashes. Cheers.

senthil
  • 1,307
  • 1
  • 11
  • 23
0
int main()
{
    int *p=3;
    int s;
    while(1) {
        s=*p;
        p++;
    }
}
sc_cs
  • 9
  • 1
  • 2
    It would be great to have some clarification :) – olyv Sep 17 '14 at 08:06
  • 1
    the p pointer will go beyond the program's address space which will be a memory error, as a process cannot access another process's memory. This will result the program to crash. pointer p is pointing to a random location in its address space, if it is incremented and dereferenced infinitely at some point it will point to another program's(process) address space. so it will crash after some time. – sc_cs Sep 17 '14 at 10:26
  • Or, hypothetically it could achieve integer overflow and wrap around, running infinitely. I'd try to use `long long` or `size_t` and start with `p` at the respective maximum value, or close to it, to crash faster. Though it's still not guaranteed to crash even in that case. – Patrick Roberts Jun 23 '15 at 00:42
0

A stylish way of doing this is a pure virtual function call:

class Base;

void func(Base*);

class Base
{
public:
   virtual void f() = 0;
   Base() 
   {
       func(this);
   }
};

class Derived : Base
{
   virtual void f()
   {
   }
};

void func(Base* p)
{
   p->f();
}


int main()
{
    Derived  d;
}

Compiled with gcc, this prints:

pure virtual method called

terminate called without an active exception

Aborted (core dumped)

Community
  • 1
  • 1
0

You can use of assembly in your c++ code BUT INT 3 is only for x86 systems other systems may have other trap/breakpoint instructions.

int main()
{
    __asm int 3;

    return 0;
}

INT 3 causes an interrupt and calls an interrupt vector set up by the OS.

0

Use __builtin_trap() in GCC or clang, or __debugbreak() in MSVC. Not handling these breakpoints/traps will lead to an unhandled breakpoint exception/crash. Other suggestions that use abort() or exit(): those may be handled by other threads, making it more difficult to see the stack of the thread that propagated the crash.

G Huxley
  • 1,130
  • 14
  • 19
0
#include <thread>

void intentionalCrash()
{
    auto noop = [](){return;};
    // Thread t1 is in a joinable state.
    // When program returns t1 will be out of scope.
    // Destructing a joinable thread creates a crash.
    std::thread t1(noop);
}

int main()
{
    intentionalCrash();
    return 0;
}
Kavit Shah
  • 495
  • 1
  • 5
  • 11
0

Simple buffer overflow code that will cause the program to crash

int main()
{
    int n[0];
    n[2] = 0;
}
Anic17
  • 712
  • 5
  • 18
-2
char*freeThis;
free(freeThis);

Freeing an uninitialized pointer is undefined behavior. On many platforms/compilers, freeThis will have a random value (whatever was at that memory location before). Freeing it will ask the system to free the memory at that address, which will usually cause a segmentation fault and make the program crash.

tmlen
  • 8,533
  • 5
  • 31
  • 84
Z Rev
  • 84
  • 1
  • 13
  • This should always crash on all systems. `int *p = (int *)-1; *p = 1;`. This is because memory address 2^64 - 1 does not exist on any system, at least, not now (assuming pointer is 8 bytes long). –  Feb 24 '22 at 08:04