精神错乱检查程序


16

精神错乱:一遍又一遍地做同样的事情,期望得到不同的结果。

编写一个程序,该程序每次运行时都会引发异常(运行时错误)。面临的挑战是有可能产生多个崩溃,而无需直接调用异常(无throw语句)并且不使用内置的随机或cpu滴答计数功能。

  • 每个可能的错误10点
  • 如果错误/崩溃发生在另一个进程或系统上,则奖励25分

规则

  1. 响应必须指出可能发生的错误以及如何产生错误。
  2. 除非每次程序运行时都使用相同的数字作为种子,否则无法使用系统(内置)随机数字生成器。
  3. 除非使用tic或cpu周期数,除非它们相对于主程序线程的开始进行计数。
  4. 允许多线程(如果未安排)。

编辑1

  1. GUID生成属于内置随机数生成器。允许自定义“本地” GUID生成。

  2. 文件的I / O允许访问文件系统,除非这样做是为了绕过规则(读取随机位或时间戳的文件)。

编辑2

  1. 调用abort()assert()违反制作疯狂软件的挑战的精神,因此,此失败模式将不会获得10分。

祝好运!


生成的Guid被视为随机的吗?
microbian

好问题。我认为熵需要神奇地实现(纸牌屋)而不是人为地实现,因此我对GUID表示不。
2014年

对于JS-崩溃的浏览器是否算作25个奖励?我可以选择应该在哪个浏览器上测试我的代码吗?
eithed

崩溃主机(浏览器或框架)可获得25分奖励积分。它必须始终崩溃。
2014年

问题是编写非确定性函数而不使用非确定性手段(也包括时钟)。C是使您可以访问未初始化的指针引用的语言之一。因此,我看到的解决方案基于未初始化的指针。对我来说,使用未初始化的指针与使用guid或random方法一样好(或坏)。
microbian

Answers:


15

爪哇,400

Java很幸运(?)有许多Exceptions和Errors。有许多Exception特定于单个类的操作的。作为最极端情况之一的一个例子,有10 Exception多个(都是的子类IllegalFormatExceptionFormatter仅用于类,而我已经花了一些时间(几乎)使所有代码都抛出。

我当前的答案有40个不同的Exceptions / Errors,它们根据System.nanoTime()某个整数的模数随机执行。

此方法只能用于测量经过时间,并且与系统或挂钟时间的任何其他概念无关。返回的值表示自某个固定但任意的原始时间以来的纳秒(也许是将来的时间,因此值可能为负)。在Java虚拟机的实例中,此方法的所有调用都使用相同的源。其他虚拟机实例可能使用其他来源。

应该允许上面的方法,因为它属于情况“ 3.不能使用tic或cpu周期的数量,除非它们相对于主程序线程的开始进行计数”

编译指令

强烈建议您使用Oracle的JRE / JDK或OpenJDK来运行代码。否则,可能不会引发某些Exception,因为其中有些依赖于引用实现的内部细节,并且我没有可靠的后备。

以下代码可使用成功编译,javac 1.7.0_11并在上产生所有异常java 1.7.0_51

  1. 要运行此代码,您需要将以下代码复制并粘贴到Unicode感知编辑器(例如Notepad ++)中,并将其保存为UTF-16(大字节序或小字节序无关紧要,只要编写BOM即可) 。

  2. 将工作目录(cd)更改为保存源代码的位置(这很重要)。

  3. 使用以下命令编译代码:

    javac G19115.java -encoding "UTF-16"
    
  4. 并运行代码:

    java G19115
    

我的代码中没有破坏性的内容,因为我也想在计算机上对其进行测试。最“危险”的代码是删除ToBeRemoved.class当前文件夹中的文件。除此之外,其余的都不会触及文件系统或网络。


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

异常和错误列表

按照在switch-case语句中声明的顺序。总共有37 Exception秒和3 Error秒。

  1. PatternSyntaxException(通过中的错误Pattern,以无聊的情况作为备份)
  2. StringIndexOutOfBoundsException(通过中的错误Pattern,以无聊的情况作为备份)
  3. IllegalArgumentException(可帮助我查找中的错误Pattern,以无聊的情况作为备份)
  4. StackOverflowError(通过中的递归实现Pattern,以无聊的情况作为备份)
  5. NumberFormatException(显示$in Pattern可以在最后一行终止符之前匹配)
  6. IllegalStateException(通过Matcher不执行匹配就访问匹配的组)
  7. ArrayIndexOutOfBoundsException(显示的令人困惑的行为split(String regex)
  8. ConcurrentModificationException(通过在for-each循环中修改Collection)
  9. ArithmeticException(通过整数除以0)
  10. ExceptionInInitializerError(通过Exception在类初始化期间引起)
  11. BufferOverflowException(java.nio.*-specific Exception
  12. BufferUnderflowException(java.nio.*特异性Exception
  13. InvalidMarkException(java.nio.*特异性Exception
  14. IndexOutOfBoundsException(通过引用替换中不存在的捕获组)
  15. ClassCastException
  16. NoSuchElementException
  17. ArrayStoreException
  18. IllegalThreadStateException
  19. EmptyStackException(java.util.Stack-specific Exception
  20. NegativeArraySizeException
  21. OutOfMemoryError(通过大数组的无聊分配)
  22. UnsupportedCharsetException
  23. IllegalCharsetNameException(显示何时Charset.isSupported(String name)返回false或throws Exception
  24. NoClassDefFoundError(显示在第一次访问方法/构造函数或字段时加载了类)
  25. InputMismatchException时(java.util.Scanner特异性Exception
  26. DuplicateFormatFlagsException(从这里到35是java.util.Formatter-specific Exception的)
  27. FormatFlagsConversionMismatchException(带有有趣的格式语法示例)
  28. IllegalFormatCodePointException
  29. IllegalFormatConversionException
  30. IllegalFormatFlagsException
  31. IllegalFormatPrecisionException
  32. IllegalFormatWidthException
  33. MissingFormatArgumentException(带有有趣的格式语法示例)
  34. MissingFormatWidthException
  35. UnknownFormatConversionException
  36. IllformedLocaleException
  37. 空指针异常
  38. AccessControlException(显示默认设置SecurityManager可用)
  39. SecurityException(通过调用Class类的构造函数)
  40. UnknownFormatFlagsException(显示Exception不能在Oracle的实现中抛出,没有备份)

感谢您的解释nanoTime以及使用此答案所做的工作。
2014年

1
Java-1 % 40 == -1还是-1 % 40 = 39
2014年

@ ja72:是-1。你得到负数了吗?(进行编辑以确保所有内容均为非负数)。
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ 2014年

Java异常的令人印象深刻的编译。+1。
ApproachingDarknessFish

5

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

以下程序依赖于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");
    };
}

以下异常将随机发生

  1. 调试断言(Vector Subscript Out of Range
  2. 堆栈溢出使用 Infinite Recursion
  3. 除以零除 Dividing by Zero
  4. 记忆不足 Allocating Huge Memory
  5. 受保护的例外 By Accessing NULL
  6. 堆栈溢出 By overwriting stack
  7. INT 3
  8. 最后,使用taskkill杀死正在运行的用户进程

1
<iostream>必要吗?
user12205 2014年

@ace:不,那是遗迹
Abhijit)

我认为调用assert()等效于引发异常。
2014年

1
在查看了此条目和其他条目之后,我决定禁止通过abort和直接调用异常assert
2014年

1
@ ja72:在Windows中,assert实际上不会引发任何异常。它通过抛出一个Debug Assert Window _crtMessageBoxW并假装调用raise(SIGABRT),最终通过exit(3)
Abhijit 2014年

5

佩尔

以下是与任何数量的perl的编译时消息一起消失的perl片段。它使用自制的伪随机数生成器生成可打印的ASCII字符,然后尝试将其作为perl执行。我不知道perl可以给出的编译时间警告的确切数量,但是肯定有至少30个这样的错误,并且它们可以以各种不同的组合出现。因此,除非它被认为是无效的,否则我会说此代码比其他解决方案要多获得一个数量级的点=)

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

来自几个不同运行的样本输出(穿插换行符):

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) (无中止或断言)

该解决方案使用当前进程ID来确定如何崩溃。

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

由于以下原因,该过程可能会终止:

  1. OutOfMemoryException(10)
  2. StackOverflowException(10)
  3. NullRefrenceException(10)
  4. DivideByZeroException(10)
  5. IndexOutOfRangeException(10)
  6. 关机将导致其他进程异常终止。(10 + 25)

10x6 + 25 = 85

编辑

在OP禁止断言和中止之后,我将其从解决方案中删除,因此所有有效的允许方法都将其降至85。


我已编辑该帖子以禁止Abort()Assert()。看看您是否仍然可以抛出这些异常而无需直接调用它们。
2014年

1
请注意,process-id总是可以被4整除,这意味着,根据action-list中元素的数量,可能永远不会抛出异常。在这种情况下,OutOfMemory,OutOfRange和Shutdown将不会被调用(除非我弄错了)。
RobIII,2014年

好吧,那他能写Process.GetCurrentProcess().Id / 4 % actions.Count吗?
麦凯2014年

2

不确定是否符合条件...

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

两个i和的元素p的未初始化,所以这可能导致任一:

  1. 如果出现段错误 i <0,则出现段错误
  2. 浮点异常,如果 i以某种方式变为0的
  3. 如果c重复增加,则段错误大于i

此外,这可能会或可能不会杀死现有应用程序(取决于 p[c]使用SIGSEGV)。

请注意,我尚未对此进行测试...因此,如果此操作无效,请发表评论


太危险而无法测试;)
2014年

1

闪闪发光

免责声明:类似于Abhijit的出色解决方案,但:

  1. 精神错乱的主要原因是托管代码通过一系列丑陋的攻击获得了本机实现细节。

  2. 这个不需要ASLR,只需要动态内存分配即可。


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

这是做什么的:

  1. 程序调用其自己的解释器(spn命令),并将空数组的描述输出到文件中。该数组是动态分配的,描述包括其内存地址。

  2. 然后,程序将打开文件,解析描述,并以整数形式获取地址。然后,它对结果值执行某种哈希处理,并执行以下错误操作之一:

    1. 类型不匹配的操作。非布尔值上的逻辑运算符(是的,语言禁止这样做!),对浮点数进行模除,添加两个字符串(有一个单独的串联运算符..,并且添加字符串是运行时异常)
    2. 像对待函数一样调用字符串。
    3. 全局常量不能符合nil语言规范(这与实现细节有关-无法将其与不存在的全局区分开)。遇到此类符号时,将引发运行时错误。

1

Python代码-用蝙蝠扑击计算机(象征性地)

我懒得完成这件事,但是有人,请接受我的想法并付诸实践!此处的目标是删除计算机的一个重要组件,并利用该部分的异常,直到最终仅对/ etc或/ usr / bin或诸如此类的重要内容执行所有命令,然后观察整个崩溃并刻录。我相信当一切崩溃时,您可以得到很多“ 25分”。:)

我将其针对Linux机器。当然,此操作必须以root用户身份运行才能获得最大的损害,如果您反复运行它,将使您的系统完全死机!

例外情况:

  1. ZeroDivisionError:整数除法或以零为模
  2. OSError:[Errno 2]没有这样的文件或目录:
  3. socket.gaierror:[Errno 8]提供的节点名或服务名,或者未知
  4. 需要您在此处添加更多

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
真棒的想法!请对其进行测试并报告!
rubik

0

TI-BASIC,130

对于您的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

致命错误(按顺序):

  1. 封存
  2. 争论
  3. 数据类型
  4. 除以0
  5. 非法巢穴
  6. 无效的点心
  7. 标签
  8. 记忆
  9. 非真实Ans
  10. 溢出
  11. 句法
  12. 未定义
  13. 变量

0

PHP代码:38(+2)个字符,5个错误,无法捕获

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

可能的错误列表:

  • 致命错误:第1行超过“ n”秒的最大执行时间

    for(;;)表示无限循环

  • 致命错误:第1行

    PHP 耗尽了2097152字节的可用内存大小(试图分配884737字节),PHP有一个php.ini文件,并且有一行写着memory_limit=,这是最大内存使用量(以字节为单位)。
    所说的部分$e.=$e++意味着$e将其自身串联的结果在每次迭代中增加1。

  • 致命错误:类名称必须是有效对象或第1行上的字符串

    可以通过类名称或将类名称作为字符串存储在var中或通过分配类的新实例并对其进行调用来调用PHP中的类。
    示例:$b='PDO';$a=new $b();$a::connect();$b::connect()->这是有效的PHP代码。
    发生此错误$e是因为nullfor(;;)循环的第一次迭代中。

  • 致命错误:函数名必须是在第1行的字符串
    同类,但功能必须是一个字符串(和$enull),或直接的函数名(例如:a()

  • 致命错误:无法在第1行上创建对临时数组表达式的元素的引用
    PHP具有foreach循环遍历数组中每个元素的循环。所述as关键字被用于指示用于存储一个新的变量的名称拷贝当前数组索引的值。
    使用时foreach($array as &$v),PHP创建一个参考,当它有&变量名的前面。

这是一个很差的分数(5个错误且无法修复)= 50分

PHP不允许捕获致命错误。


在linux上,shutdown -P +0在反引号之间添加将运行该命令(在这种情况下,将导致系统突然关闭)。

这将导致所有进程停止。

不知道这是否对奖金有效。


-2

在动作脚本中

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

在永无休止的循环中调用函数会导致解释器崩溃。


请打入您的代码,在代码的前面加四个空格,并指定长度。

1
这不是一个代码高尔夫问题。但是答案不会产生随机异常。它保证100%失败,这不会使其成为insane程序。
2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.