I once wrote a function that would crash only if you passed it the immediate value 4. Like `foo(4);` A variable containing 4 would not crash.
The function was calling the Intel assembly instruction to byte-swap an integer. These days there’s an intrinsic for that. But, this was long ago and was written for platforms that didn’t even support POSIX.
So, this function was serializing an integer to memory, byteswapping it in the process, and naturally advancing the destination pointer as well.
The bug was that I forgot to mark the input register as dirty when I set up the inline assembly.
An important thing to know about inline asm, and the reason it is so strongly discouraged these days, is that the compiler cannot see it. It’s a black box for the compiler with a limited set of manual hints — one of which I omitted. Therefore it really mucks up the compiler’s ability to pipeline instructions. And, that cancels out the performance benefits for short snippets of assembly.
Anyway… I didn’t mark the register as dirty. Therefore, the compiler was unaware that it had been modified.
So, if I called the function with a 4, it would run some black box inline assembly, write the value to memory, and then it needed to increment a pointer by the size of one integer. 4 bytes. How convenient! The compiler just saw that at compile time there was definitely a 4 in a certain register! And, the inline asm declaration didn’t declare that anything happened to that register, such as byteswapping it. So, let’s just use that “unmodified” register as a value to add to the pointer!
Advancing a pointer by a byteswapped 4 makes for a quite invalid pointer. And, technically it was the next call to the serialized that would crash when it tried to write another value to that pointer.