An update: If I don't use -O3 (in fact, if I don't use the -O flag at all), the code compiles and runs exactly as expected. I'm a little surprised (as even -O1 causes this same strange behaviour). Could this be a bug?