When code works even though it shouldn't work...

in #development2 years ago

Sometimes malformed code compiles using one compiler on one machine, but completely fails on another machine.

Common cause is defining something twice. Most linkers require that function is defined after it has been used. If function is used in more than one compilation unit, different copy might get selected by the linker for each use in different compilation units. This can cause random crashes when the duplicated function needs global data or calls other functions.

Another cause is linking some files statically and some files dynamically. When statically linked file calls function that is dynamically linked or resolved at run-time, the signature of the function must match with the function in shared library on the destination machine running the executable.


Some compilers enable or disable processor features without knowing what the destination machine can handle. This means that with some compilers, the target CPU has to be explicitly set even if the program doesn't use any of the unsupported instructions. Compiler is free to optimize the code using any specialized instructions available on the default target of the compiler. If the default target doesn't support some instruction, compiling might cause incorrect code getting generated and the resulting program might crash or perform poorly.
Common cause is when compiler vectorizes a loop or repeated memory access but the alignment of the data is not valid for the new type.

Compiler assumes the alignment match the size of the original variable, but in a lot of cases this is incorrect as some processors allow unaligned access for some registers or variable types, but not all, or there is two or mote possible instructions depending on the alignment of data.


When running the compiled program virtualized or using emulation, the virtualized or emulated CPU must support the target CPU selected with compiler. The run-time library used by the virtualization or emulation software must also match the run-time library used by the compiler.