views:

2597

answers:

34

This is a little bit of fun. Can you devise the shortest program which compiles but does nothing but immediately crash when executed? Wherefore by "crash" we mean that the program stops with an error condition (a core dump for example).

Is there a language that crashes faster (7 chars) than C using a gcc compiler? [I leave this answer for somebody to find.]

(It should be allowable to use compiler flags. Otherwise 7 wouldn't work nowadays, compiler checks became much better.)

[evaluation of results] I am unable to mark a single answer because there are multiple correct ones for multiple languages. It would not be fair to disqualify one answer for another. Please use votes for choosing best answers.

+3  A: 

In C, 33 characters:

int main(void){return*((int*)0);}
paxdiablo
you could omit the `void` in the function declaration... not best but.
jldupont
Not if you want to follow the standard, you can't. 'int main(int,char*[])' and 'int main(void)' are the only two guaranteed forms.
paxdiablo
but of course since we are being very pedantic about it :-)
jldupont
returning a dereferenced null pointer, even without the assignment, will do the trick.
Mikeage
Good point, @Mikeage, fixed.
paxdiablo
@paxdiablo: according to WHAT standard? I'm pretty sure it's legal to omit declare `int x(void) {...}` as `x() {...}` in at least C89, C++ is another story altogether.
roe
C99 which is the current standard and C1x draft both state that those two forms are the only guaranteed ones.
paxdiablo
@paxdiablo: there you go, C89 is also C. It's just not C99. Just because there's a C99 doesn't stop C89 from being C.
roe
actually Mikeage is onto some shorter solution.
Don Johe
+1  A: 
int main () { int n = 0; return 1 / n; }
Developer Art
couldn't you shorten this to int n = 1/0; ?
GSto
Couldn't that be short like `return 1/0` ?
Bobby
No, the compiler will notice it so we need to trick it.
Developer Art
That's not a complete program :-)
paxdiablo
@Developer Art:You might trick the compiler by not using compiler checks.
Don Johe
It is, if it compiles.
Don Johe
You could try `return 1/(0,0);` :)
Johannes Schaub - litb
+4  A: 

Try this in assembly:

push 0
ret

of course add the all other garbage to compile into an application.

fritzone
As you probably could build an assembler that compiles this garbage in automatically this might be valid. But I actually don't know if such an assembler exists.
Don Johe
a86 was just such a beast - needed none of that gumpff that plagued masm.
paxdiablo
+6  A: 

In C, 20 characters:

void main(){main();}

Update: Suggested by roe, 15 characters:

main(){main();}

Note: Tested with VC++ 2008.

spoulson
Not valid according to the standard :-)
paxdiablo
"`main(){return main();}`" is though.
roe
Actually it should crash after a lot of recursions. And thus "work" according to the question.
Don Johe
so is "`main(){main();}`" I guess, it'll give a warning about reaching end of non-void function though.
roe
@roe: no, it's not. You need to read the standard, if you have a spare two weeks and are feeling masochistic :-) 'int main(int,char*[])' and 'int main(void)' are the only two guaranteed forms.
paxdiablo
@paxdiablo: int is a default return type, so omitting it is ok, void is also the default parameter type, so it too may be omitted.
roe
Yes, but standard compliance is not a requirement here. It compiles and crashes in VC++ 2008.
spoulson
@roe, I really hate to be pedantic (well, I don't hate it that much) but any main prototype other than the two I mentioned is into implementation-defined behavior. See s5.1.2.2.1 of the standard.
paxdiablo
@paxdiablo: nothing wrong with being pedantic but there are earlier standards of the C language which have different requirements.
Konrad Rudolph
@paxdiablo: there isn't a 'the standard' there's a C99 standard and a C89 standard (and a bunch of others as well). `x(){...}` is perfectly valid for `int x(void) {...}` in earlier C standards. So it's valid C under that standard.
roe
Under C89 Standard it is invalid to omit the `return` statement in `main()`, so it's invalid again :)
pmg
@pmg: rats! ;) I was kind of expecting someone to point that out... I wasn't sure myself, only knew it'd produce a warning.
roe
On the other side, the function will never come to exit, so it may leave out the `return`, i think.
Johannes Schaub - litb
So, even if it isn't valid according to the standard, what's the problem? It *compiles* and *crashes*.
Martinho Fernandes
People actually compile code designed to crash, instantly, _with warnings enabled_ ?
Tim Post
+1  A: 

It depends upon the allowed max stack size for a thread. But it does crash when compiled using VC9:

int main()
{
    int a[10000000];
    return 0;
};
Naveen
Due to the condition it cannot be accepted as a "general" solution. But pretty straight forward it is.
Don Johe
+3  A: 

In QBasic:

? 1/0

(At least I think it'll still compile and then crash with divide-by-zero; it's been quite some time...)

lc
QBasic doesn't compile, QuickBASIC does :)
mgroves
Completely illiteral in Q.*Basic I do recognize the connection to the other scripting languages. The QBasic looses points in crashability due to the (completely unnecessary, of course *g*) question mark and space needed to answer a simple question with undefined answer.
Don Johe
I don't believe the space is necessary.
recursive
+21  A: 
$ cat > crash.S
hlt
$ as -o crash.o crash.S
$ ld crash.o
ld: warning: cannot find entry symbol _start; defaulting to 0000000008048054
$ ./a.out
Segmentation fault
DigitalRoss
Shortest assembler program so far.
Don Johe
+3  A: 

How about java Z? If no file exists it will "crash" with a java.lang.NoClassDefFoundError. So my answer is zero letters. If that is not valid then...

class T{}

Would "crash" with $ java T Exception in thread "main" java.lang.NoSuchMethodError: main

If you want something that actually runs, then if you are willing to abuse things a little

class T{static {int i =1/0;}}

Else

class T{public static void main(String[]a){main(a);}}
mlk
What's that space doing between T and {}? :-)
paxdiablo
+37  A: 

using python:

1/0
Adrien Plisson
3 Chars, that's indeed short.
Don Johe
I am inclined to call this a winner, especially as this works in other scripting languages too (I tried ruby and perl, obviously matlab and such should work as well.)
Don Johe
reading Vilx answer, i thought of something better: `a` will crash with a NameError.
Adrien Plisson
It also works in Ruby.
brainfck
+4  A: 

in windows powershell:

throw
Jan Willem B
The 1/0 trick does it in powershell as well. No reason to waste two innocent characters ;-)
Don Johe
:) (I just wanted to insert this smiley but SO requires comments to be at least 15 characters long, so that is 158 more innocent characters wasted. I am sorry.)
Jan Willem B
+34  A: 

I wonder if this counts...

a

This is in JavaScript. This gives the runtime error of "object not found". Since JavaScript is a dynamic language, syntactically this is actually correct. Still feels like twisting the rules. :P

Vilx-
is it actually a valid statement? won't it at least need a semicolon or something?
roe
@roe: IIRC, semicolons are used as separators between statements in Javascript, so you don't need one after the last statement.
Guffa
I should have distinguished between compiler languages and script languages, but then we'd argued about what is to be considered a script language. (This works in python as well.)
Don Johe
@roe yes this is a valid statement because javascript will perform semicolon insertion. Also, just like C, a pointless evaluation statement is allowed in javascript, `someVar;` doesn't really do anything useful, but the variable gets evaluated and it is part of the spec.
TM
generalized this might be called a general solution for object oriented scripting languages with dynamic types.
Don Johe
To get this to fail in Perl, you would either need to turn on strict, or add parentheses. `a()`
Brad Gilbert
Actually, semicolons are completely optional in JavaScript. Try it yourself! And yes - I suppose this might work in a whole range of dynamic scripting languages. I'm just not familiar with any others.
Vilx-
+79  A: 

Bah - I can crash C in 5 characters:

main;

This declares an implicit int variable called 'main'. It's global so the variable has an initial value of 0. It's C the names aren't decorated - so the linker doesn't realize that it's a var and not a function.

GCC gave me a warning - but that's all.

$ gcc crash.c 
crash.c:1: warning: data definition has no type or storage class
$ ./a.exe
Segmentation fault (core dumped)
$
Aaron
Thank's, that's at least shorter than the answer I mentioned in the question (apply a "=0" where appropriate). Explanation covers it.
Don Johe
This is even funnier if you run it under valgrind: `valgrind: the 'impossible' happened: ...`
Tim Post
+2  A: 

F# 3 characters

1/0

Does compile, though gives a warning.

David
We may call it the almost ultimate script-crasher. ;-)
Don Johe
Ah..yes, but in Haskell 1/0 computes to Infinity. Begone, ye lousy scripters!
@unknown(yahoo): Haskell would be mathematically wrong. 1/0 is not infinity, it is undefined - rearranging the equation: infinity * 0 == 1? Unlikely. I vaguely remember a lecture in my engineering course where the lecturer constructed a system where a division by zero had a valid result.
Skizz
`1/0` computes to `Infinity`, provided it is of the correct type. `Float` and `Double` will do, whereas `Integer` will complain (because it's not `Fractional` and doesn't support `/`), as will `Rational` (because zero denominator is not allowed). `Float` and `Double` types exhibit IEEE-defined behaviour, having `NaN` and `Infinity` as possible values, and are totally incorrect mathematically in that `100000000000000000000000000000000000000 + 1.0 == 100000000000000000000000000000000000000` evaluates to `True`. :-)
Michał Marczyk
+13  A: 

Perl

die
Died at test line 1.


die

prints the value of LIST to STDERR and exits with the current value of $! (errno).

Brad Gilbert
Is that technically a crash? It's doing what you asked :-)
paxdiablo
As are all programs when they crash.... This is just being a little more straightforward.
RCIX
I suppose you could replace it with `a()`
Brad Gilbert
This not only crashes as asked, it is also the most readable of all.
Martinho Fernandes
The first question I've seen where Perl had the most readable solution.
ShreevatsaR
I figured out a way to crash it in only 2 chars: http://stackoverflow.com/questions/1770427/Crash-Perl-in-two-chars/1777886#1777886
Brad Gilbert
+55  A: 

Crash with 0 characters:

$ > golf.c
$ gcc -Wl,--defsym=main=0 golf.c
$ ./a.out
Segmentation fault
Johannes Schaub - litb
and me (temporarily) without voting capabilities
rcollyer
Pssh, using special compiler flags should be included in the character count. =]
strager
+1 for this one. I've *never* seen a code golf done in 0 characters (even a Perl one).
paxdiablo
and sadly, you still haven't: command line switches count against your strokes. :)
Robert P
I did the post as an example that command line can do everything one wants (including making a shell command that appends the code into an empty file, and declaring that shell command as the compiler). There should be a more precise rule set for this question, i think.
Johannes Schaub - litb
@paxdiablo: I think an empty program was submitted to the obfuscated C contest as the shortest self-outputting program in some language. Hilarity ensued. But I may be conflated separate incidents.
Sticking to the question I absolutely allowed for arbitrary compiler flags and never counted them towards the used characters. (People think harder before posting funny questions *g*.)
Don Johe
Jack: It was IOCCC and that 'some language' was, I believe, C.
Roger Pate
+5  A: 

Brainf*ck

5 characters

+[>+]

It will take it a while, but eventually the program will run out of memory and inevitably crash.

Mark Rushakoff
Not for compilers which use wrapping for memory.
strager
Those aren't Turing complete. Where's the fun in that?
jleedev
A: 

Perl

3 characters

1/0

Produces:

Illegal division by zero at crash.pl line 1.

(still looking for something that will do it in two..)

Ether
Compilation errors? "Can you device the shortest program **which compiles** but does nothing but immediately crash when executed?"
Mark Rushakoff
MMmmm, it's suppose to compile
leppie
oh foo, now you're getting technical. :)
Ether
@Mark and leppie: That code DOES compile, as `perl -c` verifies. The error is a runtime error, and Perl just helpfully identifies the location in the program for you.
A. Rex
@A.Rex: the post was edited.
leppie
Brad Gilbert
+3  A: 

Scheme:

()

Filler text

leppie
+1  A: 

C#, 37 chars

class F{static void Main(){Main();}}

Explodes stack.

leppie
+21  A: 

X86 machine code: 1 byte

From cmd prompt in windows create file a.com containing byte F4, x86 halt instruction:

F:\>debug
-a 100
0BFD:0100 hlt
0BFD:0101
-r cx
CX 0000
:1
-n a.com
-w
Writing 00001 bytes
-q

F:\>a.com

The NTVDM CPU has encountered illegal instruction

RocketSurgeon
DOS's "*.COM" format requires zero overhead, but UNIX generally uses ELF for executables, which is similar in concept Windows's PE: headers and sections, and rather impossible to get below 45 bytes (http://www.muppetlabs.com/~breadbox/software/tiny/)
ephemient
+1  A: 

Lua, 3 characters

The divide by zero does not cause problems in Lua, but here something just as short:

a()

gives:

lua: isort.lua:1: attempt to call global 'a' (a nil value)
stack traceback:
    a.lua:1: in main chunk
    [C]: ?
gwell
Lua can divide by zero? Care to share the result?
Don Johe
Lua uses double-precision floating-point values for numbers, so `print(1/0) --> 1.#INF` on Windows and `print(1/0) --> inf` on Linux.
gwell
+4  A: 

to quote this answer:

All these answers and no Befunge? I'd wager a fair amount it's shortest solution of them all:

1

Not kidding. Try it yourself: http://www.quirkster.com/js/befunge.html

EDIT: I guess I need to explain this one. The 1 operand pushes a 1 onto Befunge's internal stack and the lack of anything else puts it in a loop under the rules of the language.

Using the interpreter provided, you will eventually--and I mean eventually--hit a point where the Javascript array that represents the Befunge stack becomes too large for the browser to reallocate. If you had a simple Befunge interpreter with a smaller and bounded stack--as is the case with most of the languages below--this program would cause a more noticeable overflow faster.

RCIX
+7  A: 

Commodore 64 BASIC:

poke 2,2:sys2

or shorter (using PETSCII graphic-char shortcuts):

pO2,2:sY2

(crash: $02 invalid opcode on MOS/CSG6510). Actually it can be done in 7 bytes (3-instructions):

lda #$02
sta $02
jmp $0002
Hernán
+1 for Commodore 64 basic. I would give you more be alas stack overflow does not let me.
mlk
@mlk: there, fixed that for you
just somebody
+8  A: 

If you're at a computer store that has TI-89s, you can crash one by typing this in:

Exec "00000000"

(that's 8 zeros)

It will yield "Illegal Instruction". Press 2nd+Left+Right+ON to reset the calc.

If you want to have more fun, do this:

Exec "4E4A4E750000"

That launches the hidden hardware test menu, including memory tests, LCD tests (draws checkerboards et al.) and more. Unfortunately, the status bar gets erased, and nothing in the calc's OS draws it back, so to clean up after yourself, reset per the instructions above, or do this:

Exec "307C56E670FF20C020C020C020C020C04E750000"
Joey Adams
You can crash it by `Exec`ing pretty much anything that isn't valid.
jleedev
+2  A: 

F#, 11 characters

box 0 :?> unit

Compiles without a warning. Crashes with: System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'Microsoft.FSharp.Core.Unit'.

Stringer Bell
Get bonus points for using language not used before.
Don Johe
+2  A: 

Perl in only 2 chars.

&a
Undefined subroutine &main::a called at test.pl line 1.
Brad Gilbert
A: 

Befunge, 1 character

pace RCIX, several answers from the shortest program to overflow the stack http://stackoverflow.com/questions/62188/stack-overflow-code-golf also apply; the shortest is the befunge program:

1

PS: Golfscript, no short answer

It seems golfscript http://www.golfscript.com/ is bad at this: I assumed there'd be a one-character stack-underflow or stack-overflow, but it seems designed not to crash. Hopefully someone who knows the language better will fill in more details.

re golfscript, there are plenty of 1 char answers, pretty much anything that consumes more than 1 arg should work.
gnibbler
+3  A: 

Factor (or Forth)

.

"Data stack underflow"

bendin
+2  A: 

Late, but whatever. PHP, 32 characters.

$r=function($z){$z($z);};$r($r);

gives Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 261900 bytes) in ...

Technically, I could also do it in 29 with

$r=function($z){$z();};$r(0);

But that isn't as much fun as infinite recursion. That, and I don't think "undefined function" errors should count as "compiling" in a scripting language, otherwise:

Z();

would be the smallest solution.

Also, instead of crashing, how about (as a script) surpassing max execution time? 8 chars:

for(;;);

My original take on that had a $i++ in the third expression of the for loop, but because PHP treats all integers as signed, instead of overflowing, it just goes negative.

Dereleased
Like the verbosity of this crashiness-analysis of PHP
Don Johe
+2  A: 

Golfscript - 1 Char

Lots of operators can do it, eg

*
(eval):1:in `initialize': undefined method `class_id' for nil:NilClass (NoMethodError)
from ../golfscript.rb:285:in `call'
from ../golfscript.rb:285:in `go'
from (eval):1:in `initialize'
from ../golfscript.rb:285:in `call'
from ../golfscript.rb:285:in `go'
from ../golfscript.rb:477
gnibbler
+1  A: 
main = undefined

In Haskell.

Rayne
A: 

0 Bytes

Using A86, you can have a zero sized source file!

Using the DOS command prompt:

> copy con crash.asm
[ctrl-z]
1 file(s) copied
> dir *.asm
11/12/2009  13:59                 0 crash.asm
> a86 crash.asm
A86 macro assembler, V4.05 Copyright 2000 Eric Isaacson
Source:
crash.asm
Object: crash.COM
Symbols: crash.SYM
> dir *.com
11/12/2009  13:59                 0 CRASH.COM
> c.com
Skizz
A: 

Groovy 3 characters

1/0

Produces

java.lang.ArithmeticException: / by zero

Don
+1  A: 

PostScript, 1 character

Like GolfScript:

*

Syntactically legal, but crashes during runtime because the token * is not defined (different reason than why GolfScript crashes).

KirarinSnow