A curious consequence of passing undefined pointer to printf

Late in the night I was writing something for SpelunkyDS. Mistakenly, I passed a pointer to printf, that was uninitialised, which definition looked like that:

Screenshot from 2018-11-18 12-10-32

Obviously, the held_sprite_width had undefined value. It could point to anything, if not set to nullptr. In get_sprite_width, all I called was:

Screenshot from 2018-11-18 12-16-46

What would it print? No, not just some rubbish, as you would expect.
It printed a “FAKE SKELETON”.

Screenshot from 2018-11-18 12-18-44.png

But hang on, why would it print a “FAKE SKELETON” anyway?
At first, I thought, that the pointer was just pointing to a const char literal that the FakeSkeleton class uses (that class is totally unrelated to the code above, it just happened that the pointer happened to be pointing somewhere in the FakeSkeleton’s memory area). Here’s some code of the FakeSkeleton class:

Screenshot from 2018-11-18 12-26-03

…but after editing the function I was sure that the printf didn’t simply use the literal “FAKE_SKELETON\n”, it called the FakeSkeleton::print_typename_newline as a whole!

I edited the function a bit:

Screenshot from 2018-11-18 12-36-13

Which caused:

Screenshot from 2018-11-18 12-36-19

Well, It could also be a compile-time optimization, where the printf(“FAKE_SKELETON%i\n”, 666) would be substituted with puts(“FAKE_SEKELETON666\n”), but I’m not sure of that.
https://stackoverflow.com/questions/37435984/why-doesnt-gcc-optimize-this-call-to-printf

If I set the width pointer to nullptr before printf, the whole effect would vanish and zeroes would be printed.

Leave a comment