Insanity Check Program


16

Follia: fare sempre la stessa cosa e aspettarsi risultati diversi.

Scrivi un programma che genera un'eccezione (errore di runtime) ogni volta che viene eseguito. La sfida è quella di avere la probabilità di produrre più di un crash, senza chiamare direttamente le eccezioni (nessuna throwistruzione) e di non utilizzare le funzioni di conteggio tick integrate o casuali della CPU.

  • 10 punti per ogni possibile errore.
  • 25 punti bonus se l'errore / crash si verifica su un altro processo o sistema.

Regole

  1. Le risposte devono indicare quali errori sono possibili e come vengono generati.
  2. Non è possibile utilizzare il generatore di numeri casuali del sistema (incorporato) a meno che non venga eseguito il seeding con lo stesso numero ogni volta che viene eseguito il programma.
  3. Non è possibile utilizzare il numero di cicli tic o cpu, a meno che non vengano conteggiati relativamente all'inizio del thread del programma principale.
  4. Il multithreading è consentito (se non incoraggiato).

Modifica 1

  1. La generazione di GUID rientra nel generatore di numeri casuali incorporato. È consentita la generazione personalizzata di GUID "homegrown".

  2. L'accesso al file system è consentito per l'I / O dei file, tranne quando fatto per bypassare le regole (leggere un file di bit casuali o timestamp).

Modifica 2

  1. Chiamare abort()o assert()violare lo spirito della sfida di creare un software folle e quindi non verranno assegnati 10 punti per questa modalità di fallimento.

In bocca al lupo!


Generare un guid è considerato casuale?
microbian

Buona domanda. Penso che l'entropia debba essere raggiunta magicamente (codice del castello di carte) e non artificialmente, quindi direi di no ai GUID.
Ja72,

Per JS - i browser che si arrestano in modo anomalo vengono conteggiati come bonus 25 o no? Posso scegliere su quale browser testare il mio codice?
Eithed

L'arresto anomalo dell'host (browser o framework) assegna i 25 punti bonus. Deve sempre andare in crash però.
Ja72,

Il problema è scrivere una funzione non deterministica senza usare mezzi non deterministici (escluso anche l'orologio). C è una delle lingue che ti dà accesso a riferimenti puntatore non inizializzati. Quindi le soluzioni che sto vedendo si basano su puntatori non inizializzati. Per me usare i puntatori non inizializzati è buono (o cattivo) come usare un metodo guid o casuale.
microbian

Risposte:


15

Java, 400

Java è benedetto (?) Con moltiException s e Errors. Esistono molti messaggi Exceptionspecifici per il funzionamento di una singola classe. Come esempio di uno dei casi più estremi, ci sono più di 10 Exceptions (tutti sono sottoclassi IllegalFormatException) dedicati alla Formattersola classe, e ho impiegato del tempo per far sì che il codice li lanci (quasi) tutti.

La mia risposta attuale presenta 40 diversi Exceptions / Errors, e vengono eseguiti casualmente a seconda del modulo di System.nanoTime()con un numero intero.

Questo metodo può essere utilizzato solo per misurare il tempo trascorso e non è correlato a nessun'altra nozione di tempo di sistema o di orologio da parete. Il valore restituito rappresenta i nanosecondi da un tempo di origine fisso ma arbitrario (forse in futuro, quindi i valori possono essere negativi). La stessa origine viene utilizzata da tutte le invocazioni di questo metodo in un'istanza di una macchina virtuale Java; è probabile che altre istanze di macchine virtuali utilizzino un'origine diversa.

Il metodo sopra dovrebbe essere consentito, dal momento che rientra nel caso "3. Impossibile utilizzare il numero di cicli tic o cpu, a meno che non vengano conteggiati relativamente all'inizio del thread del programma principale" .

Istruzioni di compilazione

Oracle JRE / JDK o OpenJDK è fortemente raccomandato per eseguire il codice. Altrimenti, alcune Eccezioni potrebbero non essere generate, poiché alcune si basano sui dettagli interni dell'implementazione di riferimento e non ho un ripiegamento affidabile.

Il codice seguente viene compilato correttamente javac 1.7.0_11e produce tutte le eccezioni sujava 1.7.0_51 .

  1. Per eseguire questo codice, è necessario copiare e incollare il codice seguente in un editor compatibile con Unicode (ad esempio Notepad ++), salvarlo in UTF-16 (Big-Endian o Little-Endian non importa finché la BOM è scritta) .

  2. Cambia la directory di lavoro ( cd) in cui è stato salvato il codice sorgente ( questo è importante ).

  3. Compilare il codice con il seguente comando:

    javac G19115.java -encoding "UTF-16"
    
  4. Ed esegui il codice:

    java G19115
    

Non c'è nulla di distruttivo nel mio codice, dal momento che voglio anche testarlo sul mio computer. Il codice più "pericoloso" è l'eliminazione del ToBeRemoved.classfile nella cartella corrente. A parte questo, il resto non tocca il file system o la rete.


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);
    }
}

Elenco di eccezioni ed errori

Nell'ordine dichiarato nell'istruzione switch-case. Ci sono 37 se Exception3 Errors in totale.

  1. PatternSyntaxException (tramite bug in Pattern, con case noiose come backup)
  2. StringIndexOutOfBoundsException (tramite bug in Pattern, con case noiose come backup)
  3. IllegalArgumentException (mi aiuta a trovare un bug Pattern, con il caso noioso come backup)
  4. StackOverflowError (tramite implementazione ricorsiva in Pattern, con case noiose come backup)
  5. NumberFormatException (mostra che $inPattern può corrispondere prima del terminatore di riga finale)
  6. IllegalStateException (tramite l'accesso ai gruppi corrispondenti Matchersenza eseguire una corrispondenza)
  7. ArrayIndexOutOfBoundsException (mostra un comportamento confuso di split(String regex) )
  8. ConcurrentModificationException (tramite la modifica di una raccolta durante un ciclo for-each)
  9. ArithmeticException (tramite divisione intera per 0)
  10. ExceptionInInitializerError (tramite cause Exception durante l'inizializzazione di una classe)
  11. BufferOverflowException ( java.nio.*SPECIFICIException )
  12. BufferUnderflowException ( java.nio.*SPECIFICIException )
  13. InvalidMarkException ( java.nio.*SPECIFICIException )
  14. IndexOutOfBoundsException (tramite riferimento a un gruppo di acquisizione inesistente in sostituzione)
  15. ClassCastException
  16. NoSuchElementException
  17. ArrayStoreException
  18. IllegalThreadStateException
  19. EmptyStackException ( java.util.Stack-specifica Exception)
  20. NegativeArraySizeException
  21. OutOfMemoryError (tramite noiosa allocazione di big array)
  22. UnsupportedCharsetException
  23. IllegalCharsetNameException (mostra quando Charset.isSupported(String name)restituisce false o genera Exception)
  24. NoClassDefFoundError (mostra che le classi vengono caricate al primo accesso a metodo / costruttore o campo)
  25. InputMismatchException ( java.util.Scanner-specifica Exception)
  26. DuplicateFormatFlagsException (da qui a 35 sono java.util.Formatter-specifiche Exception)
  27. FormatFlagsConversionMismatchException (con interessante esempio di sintassi del formato)
  28. IllegalFormatCodePointException
  29. IllegalFormatConversionException
  30. IllegalFormatFlagsException
  31. IllegalFormatPrecisionException
  32. IllegalFormatWidthException
  33. MissingFormatArgumentException (con interessante esempio di sintassi del formato)
  34. MissingFormatWidthException
  35. UnknownFormatConversionException
  36. IllformedLocaleException
  37. NullPointerException
  38. AccessControlException (mostra che il valore predefinito SecurityManagerè utilizzabile)
  39. SecurityException (tramite invocazione del costruttore di Classclasse)
  40. UnknownFormatFlagsException (mostra che questo Exceptionnon può essere generato nell'implementazione di Oracle, nessun backup)

Grazie per la spiegazione nanoTimee il lavoro svolto con questa risposta.
Ja72,

1
In Javaè -1 % 40 == -1o -1 % 40 = 39?
Ja72,

@ ja72: Lo è -1. Hai ottenuto un numero negativo? (Modificato per assicurarsi che tutto sia non negativo).
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳,

Compilazione davvero impressionante di Java Exceptions. +1.
Approaching

5

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

Il seguente programma si basa su 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");
    };
}

La seguente eccezione si verificherebbe in modo casuale

  1. Asserzione di debug (Vector Subscript Out of Range )
  2. Stack Overflow utilizzando Infinite Recursion
  3. Dividi per Zero per Dividing by Zero
  4. Out Of Memory di Allocating Huge Memory
  5. Eccezione protetta By Accessing NULL
  6. Stackoverrun By overwriting stack
  7. INT 3
  8. e, infine, utilizza taskkill per terminare un processo utente in esecuzione

1
è <iostream>necessario?
user12205,

@ace: No, era rudimentale
Abhijit,

Penso che chiamare assert()sia equivalente a lanciare un'eccezione.
Ja72,

1
Dopo aver esaminato questa e altre voci, ho deciso di vietare l'invocazione diretta delle eccezioni tramite aborte assert.
Ja72,

1
@ ja72: in Windows, assert non solleva alcuna eccezione. Lancia una finestra di Asserzione debug via _crtMessageBoxWe finge di chiamare raise(SIGABRT), che finisce viaexit(3)
Abhijit

5

Perl

Di seguito è riportato uno snippet di perl che muore con qualsiasi numero di messaggi in fase di compilazione di perl. Utilizza un generatore di numeri pseudo-casuali di origine domestica per generare caratteri ASCII stampabili e quindi tenta di eseguirli come perl. Non conosco il numero esatto di avvisi di tempo di compilazione che il perl può dare, ma ci sono sicuramente almeno 30 di questi errori e possono venire in varie combinazioni diverse. Quindi, a meno che non sia ritenuto non valido, direi che questo codice ottiene un ordine di grandezza più punti rispetto alle altre soluzioni =)

#!/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;

Esempio di output da un paio di esecuzioni diverse (intervallate da newline):

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.

3

C # (85) (Senza interruzione o asserzione)

Questa soluzione utilizza l'attuale ID processo per determinare come arrestarsi in modo anomalo.

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]();
        }
    }
}

Il processo può terminare a causa di:

  1. OutOfMemoryException (10)
  2. StackOverflowException (10)
  3. NullRefrenceException (10)
  4. DivideByZeroException (10)
  5. IndexOutOfRangeException (10)
  6. L'arresto causerà la chiusura anomala di altri processi. (10 + 25)

10x6 + 25 = 85

modificare

Dopo che l'OP non ha consentito Assert and Abort, li ho rimossi dalla mia soluzione, quindi è sceso a 85 con tutti i metodi consentiti validi.


Ho modificato il post per non consentire Abort()e Assert(). Vedi se riesci ancora a lanciare queste eccezioni senza invocarle direttamente.
Ja72,

1
Si noti che un ID processo è sempre divisibile per 4, il che significa che, a seconda del numero di elementi nell'elenco delle azioni, alcune eccezioni potrebbero non essere mai generate. In questo caso OutOfMemory, OutOfRange e Shutdown non verranno invocati (a meno che non mi sbagli).
RobIII,

bene, allora potrebbe solo scrivere Process.GetCurrentProcess().Id / 4 % actions.Count?
McKay,

2

Non sono sicuro se questo si qualifica ...

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;
}

Entrambi ie gli elementi di pnon sono inizializzati, quindi questo può causare:

  1. Un segfault se i<0
  2. Un'eccezione in virgola mobile se in iqualche modo arriva a 0
  3. Un segfault se c, dopo ripetuti incrementi, diventa maggiore dii

Inoltre, ciò può uccidere o meno un'applicazione esistente (a seconda del valore di p[c]) con un SIGSEGV.

Nota che non l'ho testato ... quindi commenta se non funziona


troppo pericoloso per provarlo;)
ajay

1

Sparkling .

Disclaimer: simile alla meravigliosa soluzione di Abhijit, ma:

  1. la principale fonte di follia è che il codice gestito ottiene un dettaglio di implementazione nativo attraverso un mucchio di brutti hack;

  2. questo non richiede ASLR, solo allocazione dinamica della memoria.


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;
}

Cosa fa questo:

  1. il programma chiama il proprio interprete ( spncomando) e genera la descrizione di un array vuoto in un file. L'array viene allocato in modo dinamico e la descrizione include il suo indirizzo di memoria.

  2. Il programma quindi apre il file, analizza la descrizione e ottiene l'indirizzo come un numero intero. Esegue quindi una sorta di hashing sul valore risultante ed esegue una delle seguenti azioni errate:

    1. Operazioni con tipi non corrispondenti. Operatori logici su non booleani (sì, la lingua lo proibisce!), Divisione modulo di numeri in virgola mobile, aggiunta di due stringhe (c'è un operatore di concatenazione separato ..e l'aggiunta di stringhe è un'eccezione di runtime)
    2. Chiamare una stringa come se fosse una funzione.
    3. Le costanti globali non possono essere in nilbase alle specifiche del linguaggio (ciò ha a che fare con un dettaglio di implementazione - non può essere distinto da un globale inesistente). Quando viene rilevato un tale simbolo, viene generato un errore di runtime.

1

Python Code - Bashing Computer with a Bat (in senso figurato)

Sono troppo pigro per finire, ma qualcuno, per favore, prendi la mia idea e corri con essa! L'obiettivo qui è quello di eliminare un componente importante del tuo computer e sfruttare le eccezioni per quella parte fino a quando non hai finalmente rm tutto / etc o / usr / bin o qualcosa di importante come quello e guardare tutto il crash e la masterizzazione. Sono sicuro che puoi segnare molti "25 punti" quando tutto si blocca. :)

L'ho indirizzato verso le macchine Linux. Questo ovviamente deve essere eseguito come root per il massimo danno e se lo esegui ripetutamente, lascerà il tuo sistema totalmente in muratura!

eccezioni:

  1. ZeroDivisionError: divisione intera o modulo per zero
  2. OSError: [Errno 2] Nessun file o directory:
  3. socket.gaierror: [Errno 8] nome nodo o nome servizio fornito o non noto
  4. Hai bisogno di aggiungere altro qui

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

4
Idea fantastica! Si prega di testarlo e riferire indietro!
rubik,

0

TI-BASIC, 130

Per la tua calcolatrice TI-84

:"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

Errori fatali (in ordine):

  1. Archivio
  2. Discussione
  3. Tipo di dati
  4. Dividi per 0
  5. Nido illegale
  6. Dim. Non valida
  7. Etichetta
  8. Memoria
  9. Ans non real
  10. straripamento
  11. Sintassi
  12. Non definito
  13. Variabile

0

Codice PHP: 38 (+2) caratteri, 5 errori, non raggiungibile

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

Elenco di possibili errori:

  • Errore irreversibile: il tempo di esecuzione massimo di 'n' secondi superato sulla riga 1

    for(;;)rappresenta un ciclo infinito

  • Errore irreversibile: dimensione della memoria consentita di 2097152 byte esauriti (tentato di allocare 884737 byte) sulla riga 1

    PHP ha un php.inifile, e c'è una riga che dice memory_limit=e qui arriva il massimo utilizzo di RAM in byte.
    La parte in cui sta dicendo $e.=$e++significa che $esarà il risultato della concatenazione di se stesso aumentata di 1 in ogni iterazione.

  • Errore irreversibile: il nome della classe deve essere un oggetto valido o una stringa sulla riga 1

    Le classi in PHP possono essere richiamate dal nome della classe o memorizzando il nome della classe come stringa in una var o assegnando una nuova istanza della classe e chiamandola .
    Esempio: $b='PDO';$a=new $b();$a::connect();$b::connect()-> questo è un codice PHP valido.
    Questo errore si verifica perché si $etrova nullnella prima iterazione difor(;;) ciclo.

  • Errore irreversibile: il nome della funzione deve essere una stringa sulla riga 1
    Come per le classi, ma le funzioni devono essere una stringa (e lo $eènull ) o il nome della funzione direttamente (esempio a():)

  • Errore irreversibile: impossibile creare riferimenti a elementi di un'espressione di matrice temporanea sulla riga 1
    PHP ha il foreachciclo che scorre attraverso ogni elemento di una matrice. La asparola chiave viene utilizzata per indicare il nome della nuova variabile utilizzata per memorizzare una copia del valore dell'indice di array corrente.
    Quando si utilizza foreach($array as &$v), PHP crea un riferimento quando si ha &davanti al nome della variabile.

È un punteggio debole (errore 5 ed è irraggiungibile) = 50 punti

PHP non consente di rilevare errori fatali.


Su Linux, aggiungendo shutdown -P +0 tra backtick eseguirà quel comando (in questo caso, il sistema si spegnerà bruscamente).

Ciò provoca l'arresto di tutti i processi.

Non sono sicuro se questo è valido per il bonus o no.


-2

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();

Le funzioni vengono chiamate in un ciclo infinito che causa l'interruzione dell'interprete.


Si prega di golf il codice, formattare il codice con quattro spazi davanti e specificare la lunghezza.
Hosch250,

1
Questa non è una domanda codegolf . Ma la risposta non produce eccezioni casuali. È garantito al 100% di fallire, il che non lo renderebbe un insaneprogramma.
Ja72
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.