16
\$\begingroup\$

Insanity: doing the same thing over and over again and expecting different results.

Write a program that just throws an exception (runtime error) each time it is run. The challenge being to have the probability to produce more than one crash, without calling the exceptions directly (no throw statements) and not to use built in random or cpu tick counting functions.

  • 10 points for each possible error.
  • 25 bonus points if the error/crash occurs on another process or the system.

Rules

  1. Responses must indicate what error(s) are possible and how they are generated.
  2. Cannot use the system (built-in) random number generator unless it is seeded with the same number each time the program runs.
  3. Cannot use the number of tics or cpu cycles, unless they are counted relatively to the start of the main program thread.
  4. Multithreading is allowed (if not encouranged).

Edit 1

  1. GUID generation falls under the built-in random number generator. Custom "homegrown" GUID generation is permitted.

  2. Accessing the file system is permitted for I/O of files except when done to bypass the rules (read a file of random bits, or timestamp).

Edit 2

  1. Calling abort() or assert() violates the spirit of the challenge of making insane software and thus no 10 points will be awarded for this mode of failure.

Good luck!

\$\endgroup\$
  • \$\begingroup\$ Is generating a guid considered as random? \$\endgroup\$ – microbian Jan 22 '14 at 17:30
  • \$\begingroup\$ Good question. I think entropy needs to be achieved magically (house of cards code) and not artificially so I would say no to GUID's. \$\endgroup\$ – ja72 Jan 22 '14 at 18:29
  • \$\begingroup\$ For JS - is crashing browsers counted as 25 bonus or not? Can I choose which browser my code should be tested on? \$\endgroup\$ – eithed Jan 22 '14 at 18:30
  • \$\begingroup\$ Crashing the host (browser or framework) awards the 25 bonus points. It must always crash though. \$\endgroup\$ – ja72 Jan 22 '14 at 18:35
  • \$\begingroup\$ The problem is to write a non-deterministic function without using non-deterministic means (excluding clock too). C is one of the languages that gives you access to uninitialized pointer references. So the solutions I am seeing are based on uninitialized pointers. To me using uninitialized pointers is as good (or bad) as using a guid or random method. \$\endgroup\$ – microbian Jan 22 '14 at 18:59

10 Answers 10

14
\$\begingroup\$

Java, 400

Java is blessed (?) with many Exceptions and Errors. There are many Exceptions that are specific to the operation of a single class. As an example of one of the most extreme cases, there are more than 10 Exceptions (all are subclass of IllegalFormatException) dedicated to Formatter class alone, and I have taken time to make the code throws (almost) all of them.

My current answer features 40 different Exceptions/Errors, and they randomly get executed depending on the modulo of System.nanoTime() with some integer.

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

The method above should be allowed, since it falls into case "3. Cannot use the number of tics or cpu cycles, unless they are counted relatively to the start of the main program thread".

Compilation Instruction

Oracle's JRE/JDK or OpenJDK is strongly recommended for running the code. Otherwise, some Exception may not be thrown, since some of them relies on the internal details of the reference implementation and I don't have a reliable fall-back.

The code below compiles successfully with javac 1.7.0_11 and produces all Exceptions on java 1.7.0_51.

  1. To run this code, you need to copy and paste the code below to a Unicode aware editor (e.g. Notepad++), save it in UTF-16 (Big-Endian or Little-Endian doesn't matter as long as the BOM is written).

  2. Change working directory (cd) to where the source code is saved (this is important).

  3. Compile the code with the following command:

    javac G19115.java -encoding "UTF-16"
    
  4. And run the code:

    java G19115
    

There is nothing destructive in my code, since I also want to test run it on my computer. The most "dangerous" code is deleting ToBeRemoved.class file in the current folder. Other than that, the rest doesn't touch the file system or the network.


import java.util.*;
import java.util.regex.*;
import java.lang.reflect.*;
import java.text.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.security.*;

class G19115 {

    // The documentation says System.nanoTime() does not return actual time, but a relative
    // time to some fixed origin.
    private static int n = (int) ((System.nanoTime() % 40) + 40) % 40;

    @SuppressWarnings("deprecation")
    public static void main(String args[]) {

        /**
         * If the code is stated to be a bug, then it is only guaranteed to throw Exception on
         * Oracle's JVM (or OpenJDK). Even if you are running Oracle's JVM, there is no
         * guarantee it will throw Exception in all future releases future either (since bugs
         * might be fixed, classes might be reimplemented, and an asteroid might hit the earth,
         * in order from the least likely to most likely).
         */

        System.out.println(n);

        switch (n) {
            case 0:
                // Bug JDK-7080302
                // https://bugs.openjdk.java.net/browse/JDK-7080302
                // PatternSyntaxException
                System.out.println(Pattern.compile("a(\u0041\u0301\u0328)", Pattern.CANON_EQ));
                System.out.println(Pattern.compile("öö", Pattern.CANON_EQ));

                // Leave this boring pattern here just in case
                System.out.println(Pattern.compile("??+*"));
                break;
            case 1:
                // Bug JDK-6984178
                // https://bugs.openjdk.java.net/browse/JDK-6984178
                // StringIndexOutOfBoundsException
                System.out.println(new String(new char[42]).matches("(?:(?=(\\2|^))(?=(\\2\\3|^.))(?=(\\1))\\2)+."));

                // Leave this boring code here just in case
                System.out.println("".charAt(1));
                break;
            case 2:
                // IllegalArgumentException

                // Bug JDK-8035975
                // https://bugs.openjdk.java.net/browse/JDK-8035975
                // Should throw IllegalArgumentException... by documentation, but does not!
                System.out.println(Pattern.compile("pattern", 0xFFFFFFFF));

                // One that actually throws IllegalArgumentException
                System.out.println(new SimpleDateFormat("Nothing to see here"));
                break;
            case 3:
                // Bug JDK-6337993 (and many others...)
                // https://bugs.openjdk.java.net/browse/JDK-6337993
                // StackOverflowError
                StringBuffer buf = new StringBuffer(2000);
                for (int i = 0; i < 1000; i++) {
                    buf.append("xy");
                }
                System.out.println(buf.toString().matches("(x|y)*"));

                // Leave this boring code here just in case
                main(args);
                break;
            case 4:
                // NumberFormatException
                String in4 = "123\r\n";
                Matcher m4 = Pattern.compile("^\\d+$").matcher(in4);

                if (m4.find()) {
                    System.out.println(Integer.parseInt(in4));
                } else {
                    System.out.println("Bad input");
                }

                // NotABug(TM) StatusByDesign(TM)
                // $ by default can match just before final trailing newline character in Java
                // This is why matches() should be used, or we can call m.group() to get the string matched
                break;
            case 5:
                // IllegalStateException
                String in5 = "123 345 678 901";
                Matcher m5 = Pattern.compile("\\d+").matcher(in5);

                System.out.println(m5.group(0));

                // The Matcher doesn't start matching the string by itself...
                break;
            case 6:
                // ArrayIndexOutOfBoundsException

                // Who is the culprit?
                String[] in6 = {
                    "Nice weather today. Perfect for a stroll along the beach.",
                    " Mmmy  keeyboaardd    iisss   bbrokkkkeeen  ..",
                    "",
                    "\t\t\t     \n\n"};
                for (String s: in6) {
                    System.out.println("First token: " + s.split("\\s+")[0]);
                }

                // Culprit is "\t\t\t     \n\n"
                // String.split() returns array length 1 with empty string if input is empty string
                //                        array length 0 if input is non-empty and all characters match the regex
                break;
            case 7:
                // ConcurrentModificationException

                List<Integer> l7 = testRandom(42);
                Integer prev = null;
                // Remove duplicate numbers from the list
                for (Integer i7: l7) {
                    if (prev == null) {
                        prev = i7;
                    } else {
                        if (i7.equals(prev)) {
                            l7.remove(i7);
                        }
                    }
                }

                System.out.println(l7);

                // This is one of the typical mistakes that Java newbies run into
                break;
            case 8:
                // ArithmeticException

                // Integer division by 0 seems to be the only way to trigger this exception?
                System.out.println(0/0);
                break;
            case 9:
                // ExceptionInInitializerError
                // Thrown when there is an Exception raised during initialization of the class

                // What Exception will be thrown here?
                Static s9 = null;
                System.out.println(s9.k);

                // A bit less interesting
                Static ss9 = new Static();

                // ----
                // A class is only initialized when any of its method/field is
                // used for the first time (directly or indirectly)

                // Below code won't throw Exception, since we never access its fields or methods
                // Static s;
                // OR
                // Static s = null;
                break;
            case 10:
                // BufferOverflowException
                short s10 = 20000;
                ShortBuffer b10 = ShortBuffer.allocate(0).put(s10);

                // Boring stuff...
                break;
            case 11:
                // BufferUnderflowException
                ShortBuffer.allocate(0).get();

                // Another boring stuff...
                break;
            case 12:
                // InvalidMarkException
                ShortBuffer.allocate(0).reset();

                // Boring stuff again...
                // reset() cannot be called if mark() is not called before
                break;
            case 13:
                // IndexOutOfBoundsException
                System.out.println("I lost $m dollars".replaceAll("[$]m\\b", "$2"));

                // $ needs to be escaped in replacement string, since it is special
                break;
            case 14:
                // ClassCastException
                Class c14 = Character.class;
                for (Field f: c14.getFields()) {
                    System.out.println(f);
                    try {
                        int o = (int) f.get(c14);
                        // If the result is of primitive type, it is boxed before returning
                        // Check implementation of sun.reflect.UnsafeStaticIntegerFieldAccessorImpl
                        System.out.println(o);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 15:
                // NoSuchElementException
                List<Integer> l15 = new ArrayList<Integer>();
                Iterator i = l15.iterator();

                System.out.println(i.next());
                // Another boring one...
                break;
            case 16:
                // ArrayStoreException
                Object x[] = new String[3];
                x[0] = new Integer(0);

                // Straight from the documentation
                // I don't even know that this exists...
                break;
            case 17:
                // IllegalThreadStateException
                Thread t17 = new Thread();
                t17.start();
                t17.setDaemon(true);

                // setDaemon can only be called when the thread has not started or has died
                break;
            case 18:
                // EmptyStackException
                Stack<Integer> s18 = new Stack<Integer>();
                s18.addAll(testRandom(43));
                while (s18.pop() != null);

                // Originally ThreadDeath, which works when running from Dr. Java but not when
                // running on cmd line. Seems that Dr. Java provides its own version of
                // Thread.UncaughtExceptionHandler that prints out ThreadDeath.

                // Please make do with this boring Exception
                break;
            case 19:
                // NegativeArraySizeException
                Array.newInstance(Integer.TYPE, -1);

                // Do they have to create such a specific Exception?
                break;
            case 20:
                // OutOfMemoryError
                Array.newInstance(Integer.TYPE, 1000, 1000, 1000, 1000);
                break;
            case 21:
                // UnsupportedCharsetException

                // UCS-2 is superseded by UTF-16
                Charset cs21 = Charset.forName("UCS-2");
                CharsetEncoder ce21 = cs21.newEncoder();

                // Just in case...
                cs21 = Charset.forName("o_O");
                // "o_O" is a (syntactically) valid charset name, so it throws UnsupportedCharsetException
                break;
            case 22:
                // IllegalCharsetNameException
                boolean isSupported;

                isSupported = Charset.isSupported("o_O");
                isSupported = Charset.isSupported("+_+");
                Charset cs22 = Charset.forName("MerryChristmas!Hohoho!");

                // This is getting stupid...
                break;
            case 23:
                // NoClassDefFoundError
                File f = new File("ToBeRemoved.class");
                f.delete();

                ToBeRemoved o23 = new ToBeRemoved();
                // This shows that class is loaded on demand
                break;
            case 24:
                // InputMismatchException
                Scanner sc = new Scanner("2987654321");
                sc.nextInt();

                // Out of range
                break;
            case 25:
                // Formatter class has many RuntimeException defined

                // DuplicateFormatFlagsException
                System.out.printf("%0000000000000000000000000000000000000000000000000005%d\n", 42);
                break;
            case 26:
                // FormatFlagsConversionMismatchException
                System.out.printf("%,d\n", Integer.MAX_VALUE);

                System.out.printf("%,x\n", Integer.MAX_VALUE);
                // Thousand separator is only applicable to base 10

                System.out.printf("%(5.4f\n", Math.PI);
                System.out.printf("%(5.4f\n", -Math.PI);

                System.out.printf("%(5.4a\n", -Math.PI);
                // '(' flag is used to surround negative value with "( )" instead of prefixing with '-'
                // '(' can't be used with conversion 'a'
                break;
            case 27:
                // IllegalFormatCodePointException
                System.out.printf("%c", Character.MAX_CODE_POINT + 1);

                // Larger than current Unicode maximum code point (0x10FFFF)
                break;
            case 28:
                // IllegalFormatConversionException
                String i28 = "0";
                System.out.printf("%d", i28);

                // A boring example
                break;
            case 29:
                // IllegalFormatFlagsException
                System.out.printf("% d\n", Integer.MAX_VALUE);
                System.out.printf("% d\n", Integer.MIN_VALUE);

                System.out.printf("%+d\n", Integer.MAX_VALUE);
                System.out.printf("%+d\n", Integer.MIN_VALUE);

                System.out.printf("% +d\n", Integer.MIN_VALUE);
                // Use either ' ' or '+ ' flag, not both, since they are mutually exclusive
                break;
            case 30:
                // IllegalFormatPrecisionException
                System.out.printf("%5.4f\n", Math.PI);
                System.out.printf("%5.4a\n", Math.PI);
                System.out.printf("%5.4x\n", Math.PI);

                // Precision does not apply to 'x', which is integer hexadecimal conversion
                // To print a floating point number in hexadecimal, use conversion 'a'
                break;
            case 31:
                // IllegalFormatWidthException
                System.out.printf("%3n");

                // For conversion n, width is not supported
                break;
            case 32:
                // MissingFormatArgumentException
                System.out.printf("%s\n%<s", "Pointing to previous argument\n");
                System.out.printf("%<s", "Pointing to previous argument");

                // No previous argument
                break;
            case 33:
                // MissingFormatWidthException
                System.out.printf("%5d %<d\n", 42); // Pad left
                System.out.printf("%-5d %<d\n", 42); // Pad right

                System.out.printf("%-d\n", 42);
                // Missing width
                break;
            case 34:
                // UnknownFormatConversionException
                System.out.printf("%q", "Shouldn't work");

                // No format conversion %q

                // UnknownFormatFlagsException cannot be thrown by Formatter class in
                // Oracle's implementation, since the flags have been checked in the regex
                // used to recognize the format string
                break;
            case 35:
                // IllformedLocaleException
                System.out.printf(new Locale("ja"), "%tA %<tB %<tD %<tT %<tZ %<tY\n", new Date());

                System.out.printf(new Locale.Builder().setLanguage("ja").setScript("JA").setRegion("JA").build(), "%tA %<tB %<tD %<tT %<tZ %<tf\n", new Date());
                // Thrown by Locale.Builder.setScript()
                break;
            case 36:
                // NullPointerException
                Pattern p36 = Pattern.compile("a(b)?c");
                Matcher m36 = p36.matcher("ac");

                if (m36.find()) {
                    for (int i36 = 0; i36 <= m36.groupCount(); i36++) {
                        // Use Matcher#end(num) - Matcher#start(num) for length instead
                        System.out.printf("%3d [%d]: %s\n", i36, m36.group(i36).length(), m36.group(i36));
                    }
                }
                break;
            case 37:
                // AccessControlException
                System.setSecurityManager(new SecurityManager());
                System.setSecurityManager(new SecurityManager());
                break;
            case 38:
                // SecurityException
                // Implementation-dependent
                Class ϲlass = Class.class;
                Constructor[] constructors = ϲlass.getDeclaredConstructors();
                for (Constructor constructor: constructors) {
                    constructor.setAccessible(true);
                    try {
                        Class Сlass = (Class) constructor.newInstance();
                    } catch (Throwable e) {
                        System.out.println(e.getMessage());
                    }
                    // The code should reach here without any Exception... right?
                }

                // It is obvious once you run the code
                // There are very few ways to get SecurityException (and not one of its subclasses)
                // This is one of the ways
                break;
            case 39:
                // UnknownFormatFlagsException
                // Implementation-dependent
                try {
                    System.out.printf("%=d", "20");
                } catch (Exception e) {
                    // Just to show the original Exception
                    System.out.println(e.getClass());
                }

                Class classFormatter = Formatter.class;
                Field[] fs39 = classFormatter.getDeclaredFields();
                boolean patternFound = false;
                for (Field f39: fs39) {
                    if (Pattern.class.isAssignableFrom(f39.getType())) {
                        f39.setAccessible(true);
                        // Add = to the list of flags
                        try {
                            f39.set(classFormatter, Pattern.compile("%(\\d+\\$)?([-#+ 0,(\\<=]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])"));
                        } catch (IllegalAccessException e) {
                            System.out.println(e.getMessage());
                        }
                        patternFound = true;
                    }
                }
                if (patternFound) {
                    System.out.printf("%=d", "20");
                }

                // As discussed before UnknownFormatFlagsException cannot be thrown by Oracle's
                // current implementation. The reflection code above add = to the list of flags
                // to be parsed to enable the path to the UnknownFormatFlagsException.
                break;
        }
    }

    /*
     * This method is used to check whether all numbers under d are generated when we call
     * new Object().hashCode() % d.
     *
     * However, hashCode() is later replaced by System.nanoTime(), since it got stuck at
     * some values when the JVM is stopped and restarted every time (running on command line).
     */
    private static List<Integer> testRandom(int d) {
        List<Integer> k = new ArrayList<Integer>();
        for (int i = 0; i < 250; i++) {
            k.add(new Object().hashCode() % d);
        }
        Collections.sort(k);

        System.out.println(k);

        return k;
    }
}

class ToBeRemoved {};

class Static {
    static public int k = 0;
    static {
        System.out.println(0/0);
    }
}

List of Exceptions and Errors

In order as declared in switch-case statement. There are 37 Exceptions and 3 Errors in total.

  1. PatternSyntaxException (via bug in Pattern, with boring case as backup)
  2. StringIndexOutOfBoundsException (via bug in Pattern, with boring case as backup)
  3. IllegalArgumentException (helps me find a bug in Pattern, with boring case as backup)
  4. StackOverflowError (via recursive implementation in Pattern, with boring case as backup)
  5. NumberFormatException (shows that $ in Pattern can match before final line terminator)
  6. IllegalStateException (via accessing matched groups in Matcher without performing a match)
  7. ArrayIndexOutOfBoundsException (shows confusing behavior of split(String regex))
  8. ConcurrentModificationException (via modifying a Collection during a for-each loop)
  9. ArithmeticException (via integer division by 0)
  10. ExceptionInInitializerError (via causing Exception during initialization of a class)
  11. BufferOverflowException (java.nio.*-specific Exception)
  12. BufferUnderflowException (java.nio.*-specific Exception)
  13. InvalidMarkException (java.nio.*-specific Exception)
  14. IndexOutOfBoundsException (via reference to non-existent capturing group in replacement)
  15. ClassCastException
  16. NoSuchElementException
  17. ArrayStoreException
  18. IllegalThreadStateException
  19. EmptyStackException (java.util.Stack-specific Exception)
  20. NegativeArraySizeException
  21. OutOfMemoryError (via boring allocation of big array)
  22. UnsupportedCharsetException
  23. IllegalCharsetNameException (shows when Charset.isSupported(String name) returns false or throws Exception)
  24. NoClassDefFoundError (shows that classes are loaded on first access to method/constructor or field)
  25. InputMismatchException (java.util.Scanner-specific Exception)
  26. DuplicateFormatFlagsException (from here to 35 are java.util.Formatter-specific Exceptions)
  27. FormatFlagsConversionMismatchException (with interesting example of format syntax)
  28. IllegalFormatCodePointException
  29. IllegalFormatConversionException
  30. IllegalFormatFlagsException
  31. IllegalFormatPrecisionException
  32. IllegalFormatWidthException
  33. MissingFormatArgumentException (with interesting example of format syntax)
  34. MissingFormatWidthException
  35. UnknownFormatConversionException
  36. IllformedLocaleException
  37. NullPointerException
  38. AccessControlException (shows that the default SecurityManager is usable)
  39. SecurityException (via invoking constructor of Class class)
  40. UnknownFormatFlagsException (shows that this Exception can't be thrown in Oracle's implementation, no backup)
\$\endgroup\$
  • \$\begingroup\$ Thanks for the explanation of nanoTime and the work done with this answer. \$\endgroup\$ – ja72 Feb 26 '14 at 16:05
  • 1
    \$\begingroup\$ In Java is -1 % 40 == -1 or -1 % 40 = 39 ? \$\endgroup\$ – ja72 Feb 26 '14 at 16:12
  • \$\begingroup\$ @ja72: It is -1. Did you get a negative number? (Edited to make sure everything is non-negative). \$\endgroup\$ – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Feb 26 '14 at 17:15
  • \$\begingroup\$ Very impressive compilation of Java Exceptions. +1. \$\endgroup\$ – ApproachingDarknessFish Mar 11 '14 at 20:51
5
\$\begingroup\$

C (Windows 7)- 80 + 25 = 105 Points

The following program relies on ASLR

#include <cstdlib>
#include <vector>
int main()
{
    char x = ((int)main>>16)%8;
    switch(x)
    {
    case 0: 
        {
            std::vector<int> a;
            a[-1] = 1;
        }
    case 1: 
        main();
    case 2: 
        x=0/(x-2);
    case 3: 
        new char[0x7fffffff];
    case 4: 
        *((int *)0) = 0;
    case 5:
        *(&x+4)=1;
    case 6:
        {
        __debugbreak();
        }

    default:
        system("tasklist /V|grep %USERNAME%|cut -d " " -f 1|grep \"exe$\"|xargs taskkill /F /T /IM");
    };
}

Following Exception would occur randomly

  1. Debug Assertion (Vector Subscript Out of Range)
  2. Stack Overflow using Infinite Recursion
  3. Divide by Zero by Dividing by Zero
  4. Out Of Memory by Allocating Huge Memory
  5. Protected Exception By Accessing NULL
  6. Stackoverrun By overwriting stack
  7. INT 3
  8. and Finally, uses taskkill to kill a running User Process
\$\endgroup\$
  • 1
    \$\begingroup\$ is <iostream> necessary? \$\endgroup\$ – ace_HongKongIndependence Jan 22 '14 at 17:48
  • \$\begingroup\$ @ace: Nope, it was vestigial \$\endgroup\$ – Abhijit Jan 22 '14 at 17:52
  • \$\begingroup\$ I think calling assert() is equivalent to throwing an exception. \$\endgroup\$ – ja72 Jan 22 '14 at 18:36
  • 1
    \$\begingroup\$ After reviewing this and other entries, I have decided to disallow direct invocation of exceptions via abort and assert. \$\endgroup\$ – ja72 Jan 23 '14 at 16:12
  • 1
    \$\begingroup\$ @ja72: In windows, assert does not actually raise any exception. It throws a Debug Assert Window via _crtMessageBoxW and pretends to call raise(SIGABRT), which ends up via exit(3) \$\endgroup\$ – Abhijit Jan 23 '14 at 17:51
5
\$\begingroup\$

Perl

Below is a perl snippet that dies with any number of perl's compile-time messages. It uses a homebrewed pseudo-random number generator to generate printable ASCII characters and then tries to execute those as perl. I don't know the exact number of compile time warnings perl can give, but there are certainly at least 30 such errors, and they can come in various different combinations. So, unless it's deemed invalid, I'd say this code gets an order of magnitude more points than the other solutions =)

#!/usr/bin/perl

use Time::HiRes "time";
use Digest::MD5 "md5_hex";
use strict;
use warnings;

my $start = time;

my $r;
sub gen {
  open(my $fh, "<", $0);
  local $/;
  <$fh>;
  $r = time-$start;
  $r = md5_hex($$.$r);
  return $r
}

sub getr {
  gen() unless $r;
  $r =~ s/^(..)//;
  my $hex = $1;
  if($hex =~ /^[018-f]/) { return getr(); }
  else { return $hex eq "7f" ? "\n" : chr hex $hex }
}

my ($str, $cnt);
$str .= getr() while ++$cnt < 1024;
system "perl", "-ce", "$str"  until  $?>>8;

Sample output from a couple of different runs (interspersed with newlines):

ski@anito:/tmp$ perl nicely.pm
Bad name after N' at -e line 1.

ski@anito:/tmp$ perl nicely.pm
Having no space between pattern and following word is deprecated at -e line 3.
syntax error at -e line 1, near "oi>"
Bad name after tNnSSY' at -e line 3.

ski@anito:/tmp$ perl nicely.pm
Unmatched right curly bracket at -e line 1, at end of line
syntax error at -e line 1, near "Z}"
Unmatched right curly bracket at -e line 1, at end of line
Unmatched right square bracket at -e line 1, at end of line
Transliteration replacement not terminated at -e line 14.

ski@anito:/tmp$ perl nicely.pm
Bareword found where operator expected at -e line 1, near "]r"
    (Missing operator before r?)
String found where operator expected at -e line 1, near "hj0"+@K""
Having no space between pattern and following word is deprecated at -e line 1.
Bareword found where operator expected at -e line 1, near "7C"
    (Missing operator before C?)
Semicolon seems to be missing at -e line 1.
Semicolon seems to be missing at -e line 2.
Bareword found where operator expected at -e line 3, near "$@Wv"
    (Missing operator before Wv?)
Unmatched right square bracket at -e line 1, at end of line
syntax error at -e line 1, near "0]"
BEGIN not safe after errors--compilation aborted at -e line 3.
\$\endgroup\$
3
\$\begingroup\$

C# (85) (Without Abort or Assert)

This solution uses current process id to determine how to crash.

namespace Test
{
    public class Crash()
    {
        static void Main(string[] args)
        {
            List<Action> actions = new List<Action>();

            Action sof = null;

            actions.Add(sof = () => { /* System.Console.WriteLine("StackOverflow"); */ sof(); });
            actions.Add(() => { System.Console.WriteLine("OutOfMemory"); while (true) actions.AddRange(new Action[1024]); });
            actions.Add(() => { System.Console.WriteLine("DivideByZero"); actions[actions.Count / actions.Count] = null; });
            actions.Add(() => { System.Console.WriteLine("OutOfRange"); actions[-1] = null; });
            actions.Add(() => { System.Console.WriteLine("NullReference"); actions = null; actions.Clear(); });
            actions.Add(() => { System.Console.WriteLine("Shutdown"); Process.Start("shutdown", "/s /f /t 0"); });

            int x = Process.GetCurrentProcess().Id % actions.Count;
            actions[x]();
        }
    }
}

Process can terminate due to:

  1. OutOfMemoryException (10)
  2. StackOverflowException (10)
  3. NullRefrenceException (10)
  4. DivideByZeroException (10)
  5. IndexOutOfRangeException (10)
  6. Shutdown will cause other processes to be abnormally terminated. (10 + 25)

10x6 + 25 = 85

Edit

After the OP has disallowed Assert and Abort, I have removed them from my solution, hence it is down to 85 with all valid allowable methods.

\$\endgroup\$
  • \$\begingroup\$ I have edited the post to disallow Abort() and Assert(). See if you can still throw these exceptions without actually invoking them directly. \$\endgroup\$ – ja72 Jan 23 '14 at 16:10
  • 1
    \$\begingroup\$ Note that a process-id is always divisible by 4 which means that, depending on the number of elements in the actions-list some exceptions might never be thrown. In this case OutOfMemory, OutOfRange and Shutdown will not get invoked (unless I'm mistaken). \$\endgroup\$ – RobIII Jan 24 '14 at 17:56
  • \$\begingroup\$ well, then he could just write Process.GetCurrentProcess().Id / 4 % actions.Count? \$\endgroup\$ – McKay Mar 7 '14 at 19:49
2
\$\begingroup\$

Not sure if this qualifies...

C

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
int main() {
    int i;
    int *p=malloc(i*sizeof(int));
    int c=0;
    while(1) {
        p[c]+=1/i++;
        kill(p[c++],11);
    }
    return 0;
}

Both i and elements of p are uninitialised, so this may either cause:

  1. A segfault if i < 0
  2. A floating point exception if i somehow gets to 0
  3. A segfault if c, after repeated increments, becomes greater than i

In addition this may or may not kill an existing application (depending on the value of p[c]) with a SIGSEGV.

Note that I have not tested this... so please comment if this does not work

\$\endgroup\$
  • \$\begingroup\$ too dangerous to test it ;) \$\endgroup\$ – ajay Jan 24 '14 at 19:56
1
\$\begingroup\$

Sparkling.

Disclaimer: similar to Abhijit's wonderful solution, but:

  1. the primary source of insanity is that managed code obtains a native implementation detail through a bunch of ugly hacks;

  2. this one doesn't require ASLR, just dynamic memory allocation.


system("spn -e 'print({});' > golf.txt");

var f = fopen("golf.txt", "rb");
fseek(f, 0, "end");
var size = ftell(f);
fseek(f, 0, "set");
var s = fread(f, size);
fclose(f);

var k = toint(substrfrom(s, 7), 16);
var n = ((k & 0xff) | ((k >> 8) & 0xff) ^ ((k >> 16) & 0xff) + ((k >> 24) & 0xff)) % 6;

const constsCantBeNil = nil;

if n == 0 {
    1 || 2;
} else if n == 1 {
    3.14159265358979323846 % 2.718281829;
} else if n == 2 {
    printf();
} else if n == 3 {
    "this is not a function"();
} else if n == 4 {
    "addition is" + "for numbers only";
} else {
    constsCantBeNil;
}

What this does:

  1. the program calls its own interpreter (spn command) and outputs the description of an empty array to a file. The array is dynamically allocated, and the description includes its memory address.

  2. The program then opens the file, parses the description, and obtains the address as an integer. It then performs some sort of hashing on the resulting value, and executes one of the following erroneous actions:

    1. Operations with mismatching types. Logical operators on non-Booleans (yes, the language prohibits this!), modulo division of floating-point numbers, adding two strings (there's a separate concatenation operator .., and addition of strings is a runtime exception)
    2. Calling a string as if it was a function.
    3. Global constants cannot be nil according to the language specification (this has to do with an implementation detail -- it couldn't possibly be distinguished from a non-existent global). When such a symbol is encountered, a runtime error is thrown.
\$\endgroup\$
1
\$\begingroup\$

Python Code - Bashing Computer with a Bat (figuratively speaking)

I'm too lazy to finish this up, but someone, please take my idea and run with it! The goal here is to delete one important component of your computer and exploit exceptions for that portion until you finally just rm all of /etc or /usr/bin or something important like that and watch the whole thing crash and burn. I'm sure you can score a lot of "25 points" when everything crashes. :)

I targeted it towards linux machines. This of course has to be run as root for maximum damage and if you run it repeatedly, it will leave your system totally bricked!

Exceptions:

  1. ZeroDivisionError: integer division or modulo by zero
  2. OSError: [Errno 2] No such file or directory:
  3. socket.gaierror: [Errno 8] nodename nor servname provided, or not known
  4. Need You to add more here

bat.py:

#!/usr/bin/env python

import os
import socket

print "You really should stop running this application... it will brick your computer. Don't say I didn't warn you!"

if os.path.exists('/tmp/selfdestruct.touch'):
    if ! os.path.exists("/etc/resolv.conf"):
        if ! os.path.exists("/etc/shadow"):
            ## until finally ##
            if ! os.path.exists("/usr/lib/"):
                 print "I'm not sure if this will even print or run... but... your computer is totally gone at this point."

            print "There goes your ability to login..."
            os.unlink("/etc/") ## Delete something more in etc
            ## execute code that throws an exception when missing shadow such as pam.d function
        print "There goes your dns ability..."
        os.unlink("/etc/shadow")
        codeGolfIP=socket.gethostbyname('codegolf.stackexchange.com') # exception #3
    print "we warned you! We're starting to get destructive!"
    os.unlink('/etc/resolv.conf')
    os.unlink('/tmp/whatever') # exception #2
else:
    os.unlink("/etc/resolv.conf")


open ('/tmp/selfdestruct.touch','a').close()
zero=0
dividebyzero=5/zero; # exception #1
\$\endgroup\$
  • 4
    \$\begingroup\$ Awesome idea! Please test it and report back! \$\endgroup\$ – rubik Feb 27 '14 at 19:59
0
\$\begingroup\$

TI-BASIC, 130

For your TI-84 calculator

:"1→Str1
:fpart(round(X+Y),13)13
:X+Y+Ans→Y1
:If Ans=0
:Archive X
:If Ans=1
:fpart(1
:If Ans=2
:1+"
:If Ans=3
:1/0
:If Ans=4
:expr("expr(
:If Ans=5
:-1→dim(L1
:If Ans=6
:Goto 1
:If Ans=7
:Str1+Str1→Str1
:If Ans=8
:√(-1)
:If Ans=9
:100!
:If Ans=10
:-
:If Ans=11
:L7
:If Ans=12
:Archive X

Fatal Errors (in order):

  1. Archive
  2. Argument
  3. Data Type
  4. Divide by 0
  5. Illegal Nest
  6. Invalid Dim
  7. Label
  8. Memory
  9. Nonreal Ans
  10. Overflow
  11. Syntax
  12. Undefined
  13. Variable
\$\endgroup\$
0
\$\begingroup\$

PHP code: 38(+2) chars, 5 error, uncatchable

<?for(;;$e.=$e++)foreach($e::$e()as&$e);

List of possible error:

  • Fatal error: Maximum execution time of 'n' seconds exceeded on line 1

    for(;;) represents an infinite loop

  • Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 884737 bytes) on line 1

    PHP has a php.ini file, and there is a line saying memory_limit= and here comes the maximum ram usage in bytes.
    The part where is is saying $e.=$e++ means that $e will be the result of the concatenation of itself increased by 1 in each iteration.

  • Fatal error: Class name must be a valid object or a string on line 1

    Classes in PHP can be called either by the class name or storing the classe name as a string in a var or by assigning a new instance of the class and calling it.
    Example: $b='PDO';$a=new $b();$a::connect();$b::connect() -> this is a valid PHP code.
    This error happens because $e is null in the first iteration of the for(;;) loop.

  • Fatal error: Function name must be a string on line 1
    Same as classes, but functions have to be a string (and $e is null) or the function name directly (example: a())

  • Fatal error: Cannot create references to elements of a temporary array expression on line 1
    PHP has the foreach loop that loops though every element in an array. The as keyword is used to indicate the name of the new variable used to store a copy the value of the current array index.
    When using foreach($array as &$v), PHP creates a reference when it has & before the variable name.

It's a weak score (5 error and is uncatchable) = 50 points

PHP doesn't allow catching fatal errors.


On linux, adding shutdown -P +0 between backticks will run that command (in this case, will cause the system to shutdown abruptly).

This causes that all the processes stop.

Not sure if this is valid for the bonus or not.

\$\endgroup\$
-2
\$\begingroup\$

In Actionscript

function g() {
   if (x==undefined) {
        h();
   } else {  
     j();
   }
}

function h() {
   if (y==undefined) {
        j();
   } else {
    x = 1; 
     g();
   }
}

function j() {
   if (z==undefined) {
      y=2; 
      h();
   } else {
      g();
   }
}

g();

Functions are called in a never ending loop causing the interpreter to crash.

\$\endgroup\$
  • \$\begingroup\$ Please golf your code, format code with four spaces in front, and specify the length. \$\endgroup\$ – Hosch250 Mar 1 '14 at 5:49
  • 1
    \$\begingroup\$ This is not a codegolf question. But the answer does not produce random exceptions. It is 100% guaranteed to fail, which would not make it an insane program. \$\endgroup\$ – ja72 Mar 2 '14 at 20:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.