Hacker News new | ask | show | jobs
by MaulingMonkey 3511 days ago
> If a particular compiler specified that casting pointers of wrong alignments causes a segfault, it'd be perfectly acceptable to rely on that behavior.

This is a great way to make your programs "fun" to port to new platforms with new compilers in terrifyingly subtle ways. I prefer not to recommend this approach to solving specific cases of undefined behavior, although if you happen to disable strict aliasing (with e.g. -fno-strict-aliasing) as an additional layer of defensive paranoia, I'm not necessarily against that.

2 comments

You can also defensively add a quick test to your program's startup code and unit tests. Startup will take a tiny bit longer, but those porting your code will be thankful if they hit the problem, double so if you manage to emit a useful diagnostic.
That would not work. Since the test may not cause any problems. While the compiler might find more optimzation opportuinities in the real program. (Just as the begining of the function did not have problem, but the for loop had.)

Just don't use undefined behavior.

1. You write a few versions of a program.

2. Users report that it started crashing sometimes in version V.

3. After lots of debugging, you discover an input that reliably crashes your program after 30 minutes.

4. A bit later, you discover that your compiler started compiling function f so that it no longer works with unaligned data/buffers of exactly 8 bytes/whatever.

5. At the start of main, you add a dummy call to f with data that reliably crashes if your compiler decides to do that optimization again.

6. The program has become worse: it now always crashes, independent of its input, but you don't have to wait 30 minutes before finding out. That makes it way less likely that you ship a binary again that has the problem. It also makes it easier to tweak source code/compiler flags/whatever until the problem disappears.

Is that perfect? Absolutely not, it is more something of last resort, but depending on the costs of crashing versus those of sometimes crashing half-way through a run, it can be an improvement.

(this technique also can be used when your code hits compiler bugs)

Well, yeah. If you have any reason to suspect that you will need to run your code on other platforms or compile with other compilers, don't do compiler-specific things. Just do it cross-platform the first time.

Hell, even if you don't think you'll ever need to do that, you should still avoid doing things that are platform or compiler specific.