top | item 19011738

(no title)

throwaway713824 | 7 years ago

This comment, while adding detail, does nothing to improve upon the original statement, which was perfectly valid, and adds nothing to the discussion. This is irrelevant pedantry that a certain stripe of c pedant delights in bludgeoning the rest of us with.

discuss

order

quietbritishjim|7 years ago

There is a genuine, non-pedantic difference between a variable having an arbitrary value and reading it causing undefined behaviour. For example, say you don't care what value a variable has so long as it's even:

    void foo() {
        int i;
        i -= i % 2;
        printf("%d %d\n", i, i);
    }
The numbers printed could be odd, because the compiler is allowed to do anything it likes. It could even print two different numbers out!

If you still think this is all pedantry that can't happen in practice, here's an example where compilers are known to do strange things when the behaviour is undefined:

    int bar(int param) {
        int uninit;
        if (param == 0) {
            uninit = 0;
        }
        baz(param);  // Some other function
        return uninit;
    }
In this snippet of code, you might think that you're safe so long as you don't look at the return value of baz(). But in fact the optimiser may conclude that param must be zero (because anything else would be undefined behaviour), so baz() is always called with a parameter of zero even if bar has another argument. An problem very similar to this was discussed as a source of possible vulnerabilities in the Linux kernel [1] (although I don't know if any actual vulnerabilities were found).

[1] https://lwn.net/Articles/575563/