Undefined Behavior Killed My Cat

83

20

Undefined Behavior Killed My Cat

It's well known that undefined behavior can kill your cat [citation needed].
But can it?

Your Task

  1. Write a program that invokes undefined behavior.
  2. Describe a scenario that starts with the above program being run, resulting in a Felis catus ending its life while in your ownership, as a result of the aforementioned UB.
  3. Estimate the probability for each stage in the scenario.
  4. Calculate the total probability that a single run of the program would kill your cat.

Rules

  1. This is a , so be creative if you can.
  2. This is a programming related challenge, so the chain of events should be mostly within the computer, not in the real world (of course, if has to reach the real world if that's where your cat is).
  3. If you choose a language that doesn't have undefined behavior, use something similar.
  4. No animals may be harmed in the production of your answer.

Scoring

Vote count plus the scenario's total probability (which can't exceed 1).

Example in C:

main(){printf();}

Scenario:

  1. printf called with garbage from the stack - undefined behavior. Probablity: 100%.
  2. The first parameter happens to be the string Your cat is ugly!. Probablity: (1/256)17 = (1.148 * 10-37)%.
  3. Seeing the message, you pick up your gun and shoot your cat. Probability: 3%.
  4. The cat dies. Probability: 93%.

Total probability: (3.202 * 10-39)%.

ugoren

Posted 2014-03-04T17:50:18.333

Reputation: 16 527

Question was closed 2016-07-22T13:30:59.290

I don't get this. For this purpose, all programs with UB are fungible. – R. Martinho Fernandes – 2016-05-09T11:08:52.337

2I don't really understand the calculation of the scoring. For example, why does number 3 give 3% as probability, and number 4 give 93%? – ProgramFOX – 2014-03-04T17:56:25.853

3@ProgramFOX, The probabilities are my estimates, that's all. Note that the probability is no more than 1, so it's no more than a tie breaker. – ugoren – 2014-03-04T17:58:01.547

1@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳, Just try not to violate rule 4. – ugoren – 2014-03-04T17:59:07.970

You might want to add in a stipulation that the total probability must be greater than 0. Are there any special rules for those of us who don't own a cat? – Josh – 2014-03-04T18:01:44.777

50>

  • Invoke undefined behavior 2) Remain inspired by the mere fact that you could invoke undefined behavior, and live a long, happy life 3) Cat dies of old age. Total probability: 100%
  • < – Geobits – 2014-03-04T18:14:54.830

    2@Geobits, but the cat's death isn't "a result of the aforementioned UB". – Oberon – 2014-03-04T18:24:31.583

    5@Oberon I'd kill myself if I couldn't come up with a single way to create an UB after programming for so long. Then the cat would no longer be in my possession. Invoking the UB keeps me alive, so that "... ending its life while in your ownership , as a result...". Ambiguous parsing FTW. – Geobits – 2014-03-04T18:28:22.567

    1Are special hardware interfaces allowed, eg. solenoids, shotguns? – Martin James – 2014-03-04T23:24:54.973

    @ProgramFOX the chance that you will shoot your cat based on said message are very low (3%). The chance of it dying when shot is high (93%). – Roberto – 2014-03-04T23:29:13.613

    @MartinJames, Everything is allowed. Will it get you upvotes? I don't know. – ugoren – 2014-03-04T23:41:03.167

    8I'd be more amused if someone reinterprets this to kill the cat command or something of that sort. – keshlam – 2014-03-05T00:24:32.517

    5-1 I love cats. Why cats? Why not killinig vermin? – V-X – 2014-03-05T09:37:07.650

    2

    @V-x Given the uncertainty, i'm pretty sure it's related to Schrödinger's cat.

    – Cees Timmerman – 2014-03-05T13:14:10.310

    1That's obvious. I wanted to compensate a bit that I'm not happy about the manifestation of cat hate. – V-X – 2014-03-05T21:46:53.200

    3@V-X, Where's the cat hate? I want to understand how UB can kill cats, so we could fight this menacing problem and save feline lives. – ugoren – 2014-03-06T02:16:31.780

    @V-X The rules say that no animals may actually be harmed. This is a clue for you that this is not to be taken seriously. If Schrödinger had made his thought experiment using a plague-infested rat, this question would have been about a plague-infested rat. The fact that *NIX has a command-line tool cat is just a serendipitous coincidence that improves the joke. – steveha – 2014-03-06T03:30:21.687

    Calling printf without a prototype is undefined behavior, period. – Kaz – 2014-03-06T08:05:16.863

    1"No animals may be harmed in the production of your answer." Can I at least harm a cat while testing after production?.... Gotta make sure to get those percentages right :D – Kevin – 2014-03-06T12:00:32.430

    5@Kevin, Sorry, but cat lovers here would downvote me to death if I let you do that. Try testing it with tofu or something. – ugoren – 2014-03-06T15:27:21.773

    When I saw the question title in the hot network questions, I first thought this had been asked at [pets.SE] :-) – Bergi – 2014-03-07T03:25:54.077

    22If a cat is to be eaten, Python is a solution. – Nicolas Barbulesco – 2014-03-07T09:09:35.573

    1Felis catus is your taxonomic nomenclature, An endothermic quadruped, carnivorous by nature; Your visual, olfactory, and auditory senses Contribute to your hunting skills and natural defenses-> Sorry had to do it :-) – Steven Wood – 2014-03-07T09:49:07.297

    4Simply letting a cat live wildly is undefined behavior. Chance of death is 100%. Do I win all your triangles? :D – Vercas – 2014-03-08T17:42:22.483

    Why is everybody struggling for a mechanism by which the felis catus dies? That's the simple part: an omnipotent being smites it. I'll leave it to everybody's imagination why that happens and how a program error my cause that situation to arise... ;-) – R.. GitHub STOP HELPING ICE – 2014-03-09T06:29:34.750

    Hmm. Maybe I'll build an automatic cat feeder with a Raspberry Pi, and implement it with UB that can cause it to malfunction. – Cruncher – 2014-05-20T18:25:37.000

    Answers

    113

    C

    Most answers to this question misinterpreted the question in that it was killing the cat process on a UNIX system. Here is a program which can cause the demise of a biological lifeform of the species Felis Cattus as specificed by the question.

    This example runs on Windows, but it could be easily ported to most UNIX operating systems by replacing iexplore -k with the command to launch an installed web browser.

    #include <stdlib.h>
    #include <stdio.h>    
    
    int main() {
        char i; // uninitialised
        printf("Redirecting you to a website which will inform you how to properly feed your cat.");
        if (i != 42) {
             system("iexplore -k https://pets.stackexchange.com/questions/tagged/cats+diet");
        } else {
             system("iexplore -k https://cooking.stackexchange.com/questions/tagged/chocolate");
        }
        return 0;
    }
    

    This program pretends to provide advise about cat diet to the user.

    It will start Internet Explorer and direct the user to pets stackexchange listing lots of helpful questions about how to feed cats. There is, however, a low (1/256) chance that it will send the user to cooking stackexchange instead listing tips how to prepare dishes containing chocolate, which is highly toxic to cats. To make matters worse, it will launch internet explorer in kiosk mode (fullscreen), which hides the address bar and is hard to escape from for a non-tech-savy user.

    This clever ruse will coax the user into feeding their cat chocolate believing that it is an appropriate diet for it, thus causing them to inadvertedly kill it.

    Philipp

    Posted 2014-03-04T17:50:18.333

    Reputation: 1 205

    3The pen is mightier than the sword! :) – Pieter Witvoet – 2014-03-05T08:46:31.863

    12This looks like the only solution so far that has any realistic chance of actually killing a cat. I am forced to upvote, although I sincerely hope no one ever actually puts it into practice. – Charles Staats – 2014-03-05T15:45:55.520

    43Internet Explorer might kill your cat all by itself. – Michael Hampton – 2014-03-05T20:35:49.950

    Chocolate is highly toxic to all sorts of domestic animals. (Cats, dogs, horses, etc. should never be fed chocolate.) Funny how it's not only yummy but actually supposed to be really good for humans... – Mason Wheeler – 2014-03-06T00:32:26.697

    @MichaelHampton I've chosen MSIE because it is the only browser you can reasonably expect to exist on every Windows system. I am pretty sure there must be a console command to open a website in the users default browser, but I was too lazy to search for it. – Philipp – 2014-03-06T13:45:00.333

    1

    Just passing the URL to ShellExecute() is sufficient.

    – Michael Hampton – 2014-03-06T13:57:36.803

    4Can you add the scenario, step by step, that kills the cat, with the probability analysis (as in the example)? As it is, this isn't a valid answer. – ugoren – 2014-03-06T19:41:44.463

    @ugoren I could, but I see no entertainment value in doing so. – Philipp – 2014-03-06T19:49:44.990

    Depending on the compiler your chances may be as low as 0 or as high as 1 - depends if the compiler uses stackguards and what kind of ;) – Voo – 2014-03-06T19:59:54.773

    1

    In addition to what @Voo said the read of uninitialized variable in C is UB (in C90 and C11 except C99 where it is a bit more complicated) so you need to calculate probability of nasal demons killing the cat as well.

    – Maciej Piechotka – 2014-03-06T23:53:31.310

    1@Philipp, I'll accept the highest voted valid answer, and to be valid it has to follow the rules. – ugoren – 2014-03-07T04:26:20.343

    1@ugoren I am a programmer, not a psychologist. – Philipp – 2014-03-07T08:10:05.297

    2@ugoren: The probability seems straightforward enough. Assuming that the probability distribution of 256 possible values of char is reasonably uniform, the odds are 1 in 256. Chocolate is toxic to cats. – Robert Harvey – 2014-03-07T17:21:28.060

    1@RobertHarvey Nope. You have to factor in the probability that the chocolate recipe will be so tasty that the greedy owner will eat it all up, with none left for poisoning kitty. Although then maybe kitty would starve to death... – AmeliaBR – 2014-03-09T00:26:59.813

    3Using Internet Explorer induces undefined behaviour in ME. — sorry, had to say that. – tomsmeding – 2014-03-23T21:42:26.720

    88

    Bash

    According to this, INT_MIN % -1 may or may not be undefined (what ???), and so might cause trouble for any language implemented in c/c++.

    #!/bin/bash
    
    cat <<< $((2**63%-1))
    

    The cat will be killed early if the parent bash process crashes, which may or may not happen.

    On my VM I get this output:

    $ ./schroedinger.sh
    ./schroedinger.sh: line 3:  7805 Floating point exception(core dumped) cat <<< $((2**63/-1))
    $ 
    

    (I don't really understand the scoring for this question, but here goes anyway)

    Calculate $((2**63%-1)). Crash always happens on bash 4.2.25, but seems to just hang on some 3.x versions. More uncertainty. I could tell you the exact probability, but due to the Heisenburg uncertainty principle I would then fall down a black hole. Or something. So I think we can safely say they probability is approximately 42%.

    Digital Trauma

    Posted 2014-03-04T17:50:18.333

    Reputation: 64 644

    shouldn't it be cat <<< $((-2**63/-1))? Didn't you lose the - sign? Even if the behavior is the same, the minimum integer should be - – mardavi – 2014-03-05T08:03:01.630

    I know the use of < and <<, but what is the purpose of <<<? (used google but couldn't find anything) – klingt.net – 2014-03-05T08:34:53.670

    4@klingt.net: It is called "Here Strings" - it is much more googlable... it is shortcut for echo $((-2**63/-1)) | cat – V-X – 2014-03-05T09:18:19.490

    Ah thanks, this is really useful! – klingt.net – 2014-03-05T09:26:54.027

    14+1 for using real cat. – Alvin Wong – 2014-03-05T15:01:24.873

    1@mardavi INT_MAX = 2^63 - 1. If we add 1 to INT_MAX, the 64bit number space wraps around and we get INT_MIN. In other words in signed 64bit integer arithmetic, 2^63 == -2^63. I could have used -2**63, but preferred the terseness without the -, since the modular arithmetic is the same in this case. – Digital Trauma – 2014-03-05T17:28:07.303

    1https://bugzilla.redhat.com/show_bug.cgi?id=579622 – Cristian Ciupitu – 2014-03-06T04:11:55.303

    1Can you add the scenario, step by step, that kills the cat, with the probability analysis (as in the example)? As it is, this isn't a valid answer. – ugoren – 2014-03-06T19:41:03.200

    INT_MIN / -1 is always undefined behavior in C/C++, what wasn't clear was whether INT_MIN % -1 (modulo not division! 2^32 is not representable in 2 complement 32bit numbers, but 0 certainly is) was undefined behavior or not. According to your link they clarified that in C11 so good riddance for that. – Voo – 2014-03-06T19:54:02.457

    This hangs my bash on OS X (requires Ctrl+C to kill); why is that? (Yes, undefined behaviour yadda yadda, but you'd expect this to at least just quit somehow...) – nneonneo – 2014-03-06T20:55:59.553

    @ugoren I edited, but I'm not sure if this is what you're looking for – Digital Trauma – 2014-03-06T22:02:18.727

    @nneonneo Yes, I got that behavior too on OSX. Sorry, I don't have an answer as to why. – Digital Trauma – 2014-03-06T22:04:02.373

    How can I upvote again given that the update mentions the probablity of killing the cat (42%)? – devnull – 2014-03-08T05:56:20.337

    @devnull I'll do it for you ;) – Doorknob – 2014-03-08T14:28:06.817

    1@Voo INT_MIN / -1 is not always undefined behaviour, because INT_MIN is allowed to be equal to -INT_MAX, in which case the result of the division is representable. – hvd – 2014-03-09T08:50:30.907

    @hvd good point. – Voo – 2014-03-09T11:19:09.237

    It's spelled Shrödinger. But +1 for reference to quantum physics! – Anonymous Pi – 2014-03-21T02:11:45.883

    @AnonymousPi Ja, mit zwei punkte. – Digital Trauma – 2014-03-21T04:10:31.547

    40

    C (sequence point)

    deadcat.c:

    #include <stdio.h>
    int main()
    {
        int i=3;
        int k=0;
        k=i+(++i);
        if (k==7)
            printf("The cat is fine. k=i+(++i) =%d\n",k);
        else
            printf("Urgent Notice: Your cat has rabies. k=i+(++i) =%d\n",k);
    }
    

    Execution (or not):

    $ clang -w deadcat.c -o deadcat; ./deadcat
    The cat is fine. k=i+(++i) =7
    $ gcc deadcat.c -o deadcat; ./deadcat
    Urgent Notice: Your cat has rabies. k=i+(++i) =8
    

    Scenario and probability

    Assuming that five percent of people running this program use clang for compiling C code (versus 90 percent using gcc and 5 percent using other C compilers):

     Probability of getting "The cat is fine."                           =  .050
     Probability of getting "Urgent Notice: Your cat has rabies."        =  .950
    
     Probability of reacting to "Your cat has rabies" by putting it down =  .040
     Probability of ignoring the notice                                  =  .900
     Probability of taking the cat to the vet for treatment              =  .060
    
     Total probability of cat living:.05 + .95 * (.90 + .06)             =  .962
     Total probability of cat dying: .95 * .04                           =  .038
     Check: Total probability of cat living or dying:                    = 1.000
    

    Explanation:

    k=i+(++i) accesses and changes "i" between sequence points. The probability is not determinable by the program; it depends upon the choice of compiler, which is made by the user. "Undefined" does not necessarily mean "random".

    See https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points

    Glenn Randers-Pehrson

    Posted 2014-03-04T17:50:18.333

    Reputation: 1 877

    4+1 for demonstrating the behavior with different compilers. – ntoskrnl – 2014-03-04T22:33:05.423

    1optimization level may also change the behavior – ratchet freak – 2014-03-05T09:00:22.453

    1@ratchet freak: Yes, but I couldn't demonstrate that with this particular problem. I tried -O0,-O1,-O2, and -O3 on a number of gcc versions ranging from gcc-4.2.3 to gcc-4.8.2, and cc-5.0 on SunOS, but all of those killed the cat. – Glenn Randers-Pehrson – 2014-03-05T16:18:42.130

    2Can you add the scenario, step by step, that kills the cat, with the probability analysis (as in the example)? As it is, this isn't a valid answer. – ugoren – 2014-03-06T19:42:31.827

    @ugoren: Working on that. It's essentially the probability of the user using clang or gcc. I can't find data on market shares but I believe clang's share isn't very big now but is increasing. It's probably higher among Stack* members than among the general public. So I'll just make a SWAG that it's 5 percent clang now, and that most of those use both clang and gcc. – Glenn Randers-Pehrson – 2014-03-06T20:02:29.937

    1I assumed that all the cats that were taken to the vet for treatment would live. Probably some of those will die from catching a communicable feline disease or from veterinary malpractice. That might change the final probabilities a little, to say .96/.04 – Glenn Randers-Pehrson – 2014-03-06T21:17:38.007

    Note that with the latest gcc that comes with XCode 5.1 this is no longer the case: gcc deadcat.c -o deadcat; ./deadcat deadcat.c:7:10: warning: unsequenced modification and access to 'i' [-Wunsequenced] k=i+(++i); ~ ^ 1 warning generated. The cat is fine. k=i+(++i) = 7 – Mike Lischke – 2014-03-31T09:51:46.850

    @MikeLischke I think that's because gcc that comes with XCode 5.1 is actually clang/LLVM. – Glenn Randers-Pehrson – 2014-03-31T15:32:08.727

    @GlennRanders-Pehrson No, they are different. Clang does "the right thing" without bringing up a warning even with -Wall, while gcc displays a warning. – Mike Lischke – 2014-04-01T07:01:28.907

    37

    C

    Backstory

    My wife inherited a cat from family. Unfortunately, I am very allergic to animals. The cat was well past its prime and should have been euthanized even before we got it, but she could not bring herself to get rid of it due to its sentimental value. I hatched a plan to end my its suffering.

    We were going on an extended vacation, but she did not want to board the cat at the veterinarian's office. She was concerned about it contracting illness or being mistreated. I created an automatic cat feeder so that we could leave it at home. I wrote the microcontroller's firmware in C. The file containing main looked similar to the code below.

    However, my wife is also a programmer and knew my feelings towards the cat, so she insisted on a code-review before agreeing to leave it at home unattended. She had several concerns, including:

    • main does not have a standards compliant signature (for a hosted implementation)
    • main does not return a value
    • tempTm is used uninitialized since malloc was called instead of calloc
    • the return value of malloc should not be cast
    • the microcontroller time may be inaccurate or roll over (similar to the Y2K or Unix time 2038 problems)
    • the elapsedTime variable may not have sufficient range

    It took a lot of convincing, but she finally agreed that theses weren't problems for various reasons (it didn't hurt that we were already late for our flight). Since there was no time for live testing, she approved the code and we went on vacation. When we returned a few weeks later, my the cat's misery was over (though as a result I've now got plenty more).

    † Entirely fictitious scenario, no worries.


    Code

    #include <time.h>
    #include <stdint.h>
    #include <stdlib.h>
    #include <string.h>
    
    //#include "feedcat.h"
    // contains extern void FeedCat(struct tm *);
    // implemented in feedcat.c
    // stub included here for demonstration only
    #include <stdio.h>
    // passed by pointer to avoid putting large structure on stack (which is very limited)
    void FeedCat(struct tm *amPm)
    {
        if(amPm->tm_hour >= 12)
            printf("Feeding cat dinner portion\n");
        else
            printf("Feeding cat breakfast portion\n");
    }
    
    // fallback value calculated based on MCU clock rate and average CPI
    const uintmax_t FALLBACK_COUNTER_LIMIT = UINTMAX_MAX;
    
    int main (void (*irqVector)(void))
    {
        // small stack variables
        // seconds since last feed
        int elapsedTime = 0;
        // fallback fail-safe counter
        uintmax_t loopIterationsSinceFeed = 0;
        // last time cat was fed
        time_t lastFeedingTime;
        // current time
        time_t nowTime;
    
        // large struct on the heap
        // stores converted calendar time to help determine how much food to
        // dispense (morning vs. evening)
        struct tm * tempTm = (struct tm *)malloc(sizeof(struct tm));
    
        // assume the cat hasn't been fed for a long time (in case, for instance,
        // the feeder lost power), so make sure it's fed the first time through
        lastFeedingTime = (size_t)(-1);
    
        while(1)
        {
            // increment fallback counter to protect in case of time loss
            // or other anomaly
            loopIterationsSinceFeed++;
    
            // get current time, write into to nowTime 
            time(&nowTime);
    
            // calculate time since last feeding
            elapsedTime = (int)difftime(nowTime, lastFeedingTime);
    
            // get calendar time, write into tempTm since localtime uses an
            // internal static variable
            memcpy(&tempTm, localtime(&nowTime), sizeof(struct tm));
    
            // feed the cat if 12 hours have elapsed or if our fallback
            // counter reaches the limit
            if(  elapsedTime >= 12*60*60 || 
                 loopIterationsSinceFeed >= FALLBACK_COUNTER_LIMIT)
            {
                // dispense food
                FeedCat(tempTm);
    
                // update last feeding time
                time(&lastFeedingTime);
    
                // reset fallback counter
                loopIterationsSinceFeed = 0;
            }
        }
    }
    

    Undefined behavior:

    For those who don't want to bother finding the UB themselves:

    There's definitely local-specific, unspecified, and implementation-defined behavior in this code, but that all should work correctly. The problem is in the following lines of code:

    struct tm * tempTm //... //... memcpy(&tempTm, localtime(&nowTime), sizeof(struct tm));
    memcpy overwrites the tempTM pointer instead of the object it points to, smashing the stack. This overwrites, in addition to other things, elapsedTime and loopIterationsSinceFeed. Here's an example run where I printed out the values:

    pre-smash : elapsedTime=1394210441 loopIterationsSinceFeed=1 post-smash : elapsedTime=65 loopIterationsSinceFeed=0


    Probability of killing the cat:

    • Given the constrained execution environment and build chain, the undefined behavior always occurs.
    • Similarly, the undefined behavior always prevents the cat feeder from working as intended (or rather, allows it to "work" as intended).
    • If the feeder does not work, it is extremely likely the cat will die. This is not a cat that can fend for itself, and I failed to ask the neighbor to look in on it.

    I estimate that the cat dies with probability 0.995.

    jerry

    Posted 2014-03-04T17:50:18.333

    Reputation: 489

    It's the (first) & in the memcpy, right? – Score_Under – 2014-03-07T02:39:49.183

    @Score_Under Yes, let me edit the answer a little. I played around with other ways to harness undefined behavior, but most were even more obvious. – jerry – 2014-03-07T16:03:09.553

    1+1 for killing a cat, not cat. – Kevin – 2014-03-23T18:10:33.877

    31

    bash

    Classic version

    cat & # This is your cat.
    pkill -$RANDOM cat
    

    Has the advantage of killing all cats in its range.

    Note that the process is stopped immediately, so the only way to end it with a single invocation of pkill is to send SIGKILL (9).

    Therefore:

    p(SUCCESS) = p(RANDOM == 9) = 0.0275 %


    Quantum version

    schroedinger=/dev/null             # We'll need this guy.
    heisenberg=/dev/urandom            # Also needed, for uncertainty principle.
    cat $heisenberg > $schroedinger &  # Steal cat from Heisenberg and give it to Schrödinger.
    felix=$!                           # Name cat for future references.
    exec 2> $schroedinger              # Send all results to Schrödinger.
    kill -SIGSTOP $felix               # Catch Felix and put him into a box.
    if (($RANDOM & 1))                 # Flip a coin.
    then kill $felix                   # Heads: Kill! Kill! Kill!
    fi                                 # By now, Felix can be thought of as both alive and dead.
    read -sn 1                         # Wait for somebody to open the box.
    kill -SIGCONT $felix               # Let him open it.
    if ps p $felix > $schroedinger     # Let Schrödinger check on Felix.
    then echo The cat is alive.        # Hooray for tails!
    else echo The cat is dead.         # At least, now we know.
    fi                                 # This concludes the experiment.
    kill -SIGKILL $felix               # Felix is no longer required.
    

    Probability of killing the cat during the experiment: 50 %

    Dennis

    Posted 2014-03-04T17:50:18.333

    Reputation: 196 637

    +1 But it's rather more likely than that I think. SIGINT (2), SIGQUIT (3), SIGABRT (6), SIGPIPE (13) and SIGTERM (15), at least, kills it here. – l0b0 – 2014-03-05T09:27:20.210

    @l0b0: It doesn't, at least not immediately. cat & attempts to read from the terminal, but can't. Any of the signals you mentioned (and a few more) will work if you send SIGCONT (18) afterwards. Also, I agree that hanging up and terminating the cat would be the same as killing it, but interrupting it doesn't seem satisfactory... :P – Dennis – 2014-03-05T12:22:03.720

    3Undefined behavior is using a feature of a language that has been specified as undefined. That is, the language designers have purposefully left the behavior of some syntactical construct undefined in order to make implementation easier, or to indicate that the construct should never be used in any valid program. Undefined behavior usually has nothing to do with random number generation, and there is no undefined behavior being used here. – OregonTrail – 2014-03-05T15:38:07.350

    @OregonTrail: The rules say If you choose a language that doesn't have undefined behavior, use something similar. Bash doesn't have undefined behavior, so I used random numbers. – Dennis – 2014-03-05T15:43:28.920

    3There's plenty of undefined behavior in bash's environment which can be used. For example, the answer by @DigitalTrauma Bash's printf also uses the system's printf which has plenty of undefined behavior. – OregonTrail – 2014-03-05T15:50:03.650

    Just explaining why I don't think I broke the rules. – Dennis – 2014-03-05T16:11:48.563

    17

    C

    Note that this only works on linux.

    main() {
      FILE *f = fopen("skynet", "w");
      srand(time(0));
      while(rand() != rand())
        fputc(rand()%256, f);
      fclose(f);
      system("chmod +x skynet");
      system("./skynet");
    }
    
    1. Write random data to a file and invoke it (100%)
    2. Random data happens to be the source code to skynet (1x10^-999999999999999999999999999999999999999999999999999999999999999, aprox.)
    3. Cat dies in resulting doomsday (99.999%)

    Total probability: 1x10^-999999999999999999999999999999999999999999999999999999999999999, aprox.

    Josh

    Posted 2014-03-04T17:50:18.333

    Reputation: 2 783

    hmmmm, what is skynet? – Display Name – 2014-03-04T22:20:06.310

    20Where's the undefined behavior? – ugoren – 2014-03-04T23:45:14.003

    @SargeBorsch: http://en.wikipedia.org/wiki/Skynet_(Terminator)

    – cHao – 2014-03-06T04:23:30.583

    1@ugoren I think running a file with random contents isn't really defined. – 11684 – 2014-03-06T08:33:59.653

    2@11684, If the contents happen to be the code to skynet, an skynet's programmers know what they're doing, there's no undefined behavior. – ugoren – 2014-03-06T15:29:14.517

    @ugoren running a file containing random ascii characters is pretty undefined. The issue is not what it could contain, but that we don't know ahead of time what it contains. – Josh – 2014-03-11T13:22:26.667

    15

    C++

    Your Cat is Both Dead and Alive until you are Curious. Then you realize that there is a 0.5 probability that your Cat is Dead.

    #ifdef WIN32
    #pragma warning(disable: 4700)
    #endif
    #include <random>
    #include <iostream>
    #include <vector>
    #include <climits>
    #include <memory>
    class Cat
    {
    public:
        enum class State {DEAD, ALIVE};
        Cat()
        {
            int x; // Uninitialized Variable on Stack
            if (x % 2 == 0) // Is the Uninitialized Variable even? 50-50
            {
                m_dead = State::DEAD;
    
            }
            else
            {
                m_dead = State::ALIVE;
            }
        };
        operator State() //Check if your Cat is Dead / Alive
        {
            if (m_dead == State::DEAD)
            {
                delete this; //Boom Cat is dead
                std::cout<<"Your Curiosity killed your Cat"<<std::endl;
                return false;
            }
            return m_dead;
        }
    private:
        State m_dead;
    };
    
    class Schrödinger
    {
    public:
        Schrödinger(size_t size):m_size(size)
        {
            for(size_t i = 0; i < size; i++)
            {
                cats.push_back(new Cat());
            }
        }
        ~Schrödinger()
        {
        }
        void Curiosity()
        {
            std::default_random_engine generator;
            std::uniform_int_distribution<int> distribution(0,m_size);
            if(*cats[distribution(generator)] == Cat::State::ALIVE)
            {
                std::cout<<"You Cat is alive and still kicking" <<std::endl;
            }
        }
    private:
        std::vector<Cat *> cats;
        size_t m_size;
    };
    int main()
    {
        int size;    
        std::cout<<"How Big is Your Example Space ?";
        std::cin>>size;
        Schrödinger your(size);
        your.Curiosity();
        return 0;
    
    }
    

    Abhijit

    Posted 2014-03-04T17:50:18.333

    Reputation: 2 841

    can you access this->m_dead after delete this? – Bryan Chen – 2014-03-05T01:37:07.533

    @BryanChen: A return was missing. THank you for pointing it out :-) – Abhijit – 2014-03-05T05:32:46.200

    ö doesn't seem to be a valid symbol in C++. Maybe replace it with oe. – Ruslan – 2014-03-06T10:25:48.820

    13

    C

    Runs on Linux.

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    void f(char x) {
        if(sleep(1)==x) system("killall cat");
    }
    int main() {
        char x; // uninitialised
        system("cat /dev/urandom &");
        f(x);
        return 0;
    }
    

    Probability of killing the cat: 1/256 (The sleep(1) returns 0, so it will be killed if x is zero.)

    As a bonus, it kills all cats currently running on your system.


    If you hate cats so much, I present to you:

    The Cat Centipede (Bash)

    echo "Hello World"|cat|cat|cat
    

    Based on the fact that, in The Human Centipede (First Sequence), all three dogs of the dog centipede died, and two out of three people of the human centipede died, I estimate that the probability of killing one cat is 5/6.

    user12205

    Posted 2014-03-04T17:50:18.333

    Reputation: 8 752

    Cat Centipede is truly funny – Display Name – 2014-03-04T22:21:25.123

    The cat centipede should be the "actual" answer. – Ismael Miguel – 2014-03-04T23:06:48.923

    @Ismael Miguel You're probably right, I've removed the C code. At first it was meant to be a joke, but later I realised that I could rephrase it to make it an actual answer. – user12205 – 2014-03-04T23:21:25.790

    You can keep your C code, I have and had nothing against it. I just though that the bash version was more suitable as an answer. – Ismael Miguel – 2014-03-04T23:45:42.607

    @Ismael Miguel Nah, that C code was quite stupid anyway – user12205 – 2014-03-04T23:48:43.767

    I didn't though so. But now you have a funny answer in bash. – Ismael Miguel – 2014-03-05T00:13:28.737

    9

    int foo() {}
    
    void main() {
        int x = foo();
    }
    

    Reading a value of function supposed to return a value results in undefined behaviour. Now, it is obvious,[citation needed] that "Every time you reach undefined behaviour, God kills a kitty." Using this we conclude:

    • Probability you reach undefined behaviour - 100%
    • Probability it is your kitty which god killed - 1/200 000 000 see why
    • So probability is 0.0000005%

    Can be easily extended by loop to exterminate all cats in the world.

    Petr

    Posted 2014-03-04T17:50:18.333

    Reputation: 191

    @xfix incorrect – it's UB in C++. see here

    – Ven – 2016-05-09T10:48:07.353

    5Your probability is 100 times too high (200M cats, not 2M). – ugoren – 2014-03-04T23:43:34.137

    I have in in percents. :) – Petr – 2014-03-04T23:50:31.673

    1It's in percents, and still it's 100 times too high. – ugoren – 2014-03-05T02:36:46.183

    You are right, I cannot read numbers anymore, apparently. – Petr – 2014-03-05T11:44:52.827

    This is incorrect. UB is only invoked if the caller attempts to use the return value. Otherwise it is completely legal and well-defined to walk off the end of a function with non-void return type. – R.. GitHub STOP HELPING ICE – 2014-03-06T20:14:30.927

    Well, this answer says otherwise http://stackoverflow.com/a/367662/1715185

    – Petr – 2014-03-06T22:09:27.477

    @R..: @Petr: This answer is not correct. In C, according to C99 specification, 6.9.1.12, "If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.". This is allowed, because before ANSI C, void type did not exist. C++ doesn't disallow that, therefore it's also allowed in C++.

    – Konrad Borowski – 2014-03-23T10:19:09.363

    @xfix You are right, the code I provided could potentially result to undefined behaviour, but would not as I wrote it. I added the code to satisfy the condition value of the function call is used by the caller. – Petr – 2014-03-25T16:07:59.273

    9

    JavaScript

    ~"cat".localeCompare("dead")
      ? "Cat is dead"
      : "Cat is fine"
    

    Execution:

    • Chrome: Results in "Cat is fine"
    • Firefox: Results in "Cat is dead"

    Explanation:

    15.5.4.9 String.prototype.localeCompare (that)

    The two Strings are compared in an implementation-defined fashion

    Quoting Glenn Randers-Pehrson, the probability is not determinable by the program; it depends upon the choice of browser, which is made by the user.

    Florent

    Posted 2014-03-04T17:50:18.333

    Reputation: 2 557

    Not reproducible on FF 27. Which version are you testing on? – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-03-05T19:09:55.410

    -1: undefined behavior and implementation-defined behavior are completely different. – whitequark – 2014-03-05T22:26:09.970

    @n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ FF 28. Do not forget the ~! – Florent – 2014-03-05T23:16:38.087

    2@whitequark No they aren't. It is a defined function with an undefined outcome. Ergo undefined behavior. – George Reith – 2014-03-07T10:38:31.317

    @GeorgeReith If we're talking about these terms in context of C: the outcome is defined by implementation. If outcome was undefined, the program could navigate to http://reddit.com instead of comparing strings and it would be legal. I suggest you consult ISO/IEC 9899:1999, section 3.4.

    – whitequark – 2014-03-08T11:39:05.920

    1

    @whitequark I don't see any C here. As far as JavaScript is concerned Does JavaScript have undefined behaviour seems to think that implementation defined behaviour is passable.

    – George Reith – 2014-03-08T12:03:22.810

    @GeorgeReith sure. however, JavaScript terminology doesn't include "undefined behavior", and using it in spite of that is needlessly confusing (as shown by this exchange), especially if discussed sideways with C. – whitequark – 2014-03-09T11:54:56.743

    1@whitequark nobody else is confused. A word is a word, I don't need a committee to tell me what it means. – George Reith – 2014-03-09T13:04:21.530

    5

    Java (Garbage Collection)

    Although code can invoke System.gc() is does not make sure that the Garbage Collector will collect all of the unused objects. Thus, for the following code, it's unpredictable if the cat will be killed or not.

    public class KillTheCat {
        public static void main(String[] args) throws InterruptedException {
            KillTheCat cat = new KillTheCat();
            cat = null;
            System.gc();
            System.out.println("Cat is still alive.");
        }
    
        @Override
        protected void finalize() throws Throwable {
            System.out.println("Cat has been killed.");
            System.exit(0);
        }
    }
    

    The probability cannot be calculated.

    Note that there's still a chance that the cat will be "revived" if there's a context switch in the GC thread after sysout and before System.exit(0) but I preferred not to cover it to keep the concept simpler.

    user3001267

    Posted 2014-03-04T17:50:18.333

    Reputation: 171

    As far as I understand, "nearly always" matches the unpredictability aspect of the question. – user3001267 – 2016-06-08T00:40:55.183

    1This is no good. This code as written will nearly always print both. Better would be to add System.out.close() after the System.out.println("Cat is still alive."); line. – durron597 – 2014-03-05T13:19:17.377

    5

    Anybody having thought of really killing (a) cat?

    [ $[ $RANDOM % 6 ] == 0 ] && rm /bin/cat || echo Meow
    

    Probabilitiy of cat dying

    For the probability... I guess we need to distinguish some cases:

    1. Windows user: Probably will not be able to execute it. Chance of dying cats is very low, can safely be assumed to be zero. If he's got Cygwin installed, he'll count as unix user.
    2. Unix user, running without root privileges: Killing the cat will fail.
    3. Unix user, running with root privileges: While each call will only kill cats with a chance of 1/6, he will very probably repeat it until something unexpected occurs. Without loss of generality, I assume cat will definitely die.

    Overall probability depends on how the users are mixed and is hard to determine. But we can surely say: Windows is a safe place for kittens.

    Testing for obedience of the rules

    No animals may be harmed in the production of your answer.

    This did not kill animals, the answer is approved by the American Humane Association.

    $ file `which cat`
    /bin/cat: Mach-O 64-bit executable x86_64
    

    clearly proves that cat is no animal (as long file does not know any kind of hidden file type inheritance).

    Jens Erat

    Posted 2014-03-04T17:50:18.333

    Reputation: 261

    5

    C

    If your cat's name is too long, it dies. gets causes cat deaths, along with other problems.

    #include <stdio.h>
    #include <stdbool.h>
    
    /* Stores instances of cats. */
    struct cat {
        /* 6 bytes are more than enough. */
        char name[6];
    
        /* Stores whether your cat is dead. */
        bool dead;
    };
    
    int main(void) {
        /* This is your cat. */
        struct cat your_cat;
        /* It lives. */
        your_cat.dead = false;
        /* Determine its name. */
        printf("Your cat name: ");
        gets(your_cat.name);
    
        /* Output the cat state. */
        const char *state = your_cat.dead ? "dead" : "alive";
        printf("Your cat, %s, is %s.\n", your_cat.name, state);
    
        return your_cat.dead;
    }
    

    Konrad Borowski

    Posted 2014-03-04T17:50:18.333

    Reputation: 11 185

    4

    Haskell

    import Acme.Missiles
    import System.IO.Unsafe
    main = print (unsafePerformIO launchMissiles, undefined)
    

    Here, we apply unsafePerformIO to an action that has observable side-effects. That is always undefined behaviour, at least so is the order of effects. So either will the program first crash on trying to evaluate undefined (that one, ironically, is not undefined behaviour: it must never yield a value that would allow the program to carry on with something else), or it will in fact incur the serious international side-effects. In that case, survival chance is only 0.001%.

    Probability of killing the cat thus: 49.9995%.

    ceased to turn counterclockwis

    Posted 2014-03-04T17:50:18.333

    Reputation: 5 200

    3

    Thue

    Since the question allows for a language that doesn't have undefined behavior as long as the effect is similar, I choose Thue for its non-determinism in choosing which rule to execute when there are more than 1 rule which can be applied on the current state.

    The program will be fed into the controller for a microwave oven, inside of which is my cat. The door to the microwave oven is closed and reinforced by a zip tie. The output of the program will decide whether the microwave oven starts to microwave the cat or not.

    • If the output is 0, we will start the experiment on the effect of long exposure of microwave on live mammal (which is currently insufficiently researched).
    • If the output is 1, we will just be satisfied with the fact that the cat has just lost one of its 9 lives and let it out.

    i::=~0
    i::=~1
    ::=
    i
    

    The probability of killing the cat is dependent on the implementation of the interpreter, but let's say it's 50%. Then the probability that the cat will die is 0.5.

    n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

    Posted 2014-03-04T17:50:18.333

    Reputation: 5 683

    Non-determinate does not mean non-defined – Score_Under – 2014-03-07T02:52:02.080

    @Score_Under: What is your point? – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-03-07T02:52:52.557

    The question asks for undefined behaviour, which involves leveraging behaviour of a language which will compile and run, but has no specification as to what it should actually do. Hinging things on Math.random() for example is not undefined behaviour, just unpredictable behaviour. – Score_Under – 2014-03-08T13:30:48.403

    1@Score_Under: In the question 3. If you choose a language that doesn't have undefined behavior, use something similar. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-03-08T14:08:34.793

    1

    Java

    According to spec java.util.Date will have undefined behaviour. So try your luck:

    import java.util.Date;
    
    public class App3
    {
        public static void main (String args[])
        {
            String aliveOrDead;
            Date d = new Date(-1000,-1000,-1000);
            aliveOrDead = (d.getTime()<0)? "dead" : "alive";
            System.out.println("The cat is:" +aliveOrDead );
        }
    }
    

    RobAu

    Posted 2014-03-04T17:50:18.333

    Reputation: 641