Hacker News new | ask | show | jobs
by Lockal 4405 days ago
UB abuse in C/C++ Linux x86-64 (works with gcc/clang/icc with any optimization level):

  #include <stdio.h>

  int main() {
    double x;
    printf("Input any number:\n> ");

    if (scanf("%lf", &x) == 1) {
      printf("Is 2 + 2 really equals %g? Let's try!\n", x);
      printf("2 + 2 = %g\n", 2 + 2);
    } else {
      printf("Invalid input!\n");
    }
  }
Output:

  Input any number:
  > 5
  Is 2 + 2 really equals 5? Let's try!
  2 + 2 = 5
Explanation: linux x86-64 calling convention uses xmm registers to pass fp values. In the first printf we initialize %xmm0 with some value. In the second printf we put integer 4 in %esi, however printf reads value again from %xmm0. Here is an assembly in GCC explorer (sorry for shortened link, that's how GCC explorer works): http://goo.gl/mY9phE