-1
/*
    Can you interchange the execution order of the printf() statements?!
    Notes:
     - problem occurs in 32-bit Ubuntu 14.04
     - problem occurs in 64-bit Ubuntu 14.04
*/

#include <stdio.h>

int * addition(int a, int b) {
    int c = a + b;
    int *d = &c;
    return d;
}

int main(void) {
    int result = *(addition(1, 2));
    int *result_ptr = addition(1, 2);
    printf("result = %d\n", *result_ptr);
    printf("result = %d\n", result);
    return 0;
}

The question says that exchanging order of lines printf("result = %d\n", *result_ptr); and

printf("result = %d\n", result);

will result in different output. But when I compiled and run both codes in Ubuntu the results are the same, both output is 3 3. The problem is suppose to happen in Ubuntu only.

Benjamin
  • 13
  • 2
  • Local variables are destroyed upon the exit of the function. Accessing them leads to UB. – Haris Sep 12 '15 at 13:41
  • Your program exhibits UB as you return the address of a local variable from `addition`. Anything could be the result. "_exchanging order of lines will result in different output_" -- UB means anything can happen. – Spikatrix Sep 12 '15 at 13:41
  • possible duplicate of [Why reverse the order of printf() gives different output?](http://stackoverflow.com/questions/25599936/why-reverse-the-order-of-printf-gives-different-output) and [Some issue concerning fprint and pointers](http://stackoverflow.com/questions/32462244/some-issue-concerning-fprint-and-pointers) and maybe [Use of pointers](http://stackoverflow.com/questions/18573856/use-of-pointers) – Spikatrix Sep 12 '15 at 13:50

1 Answers1

2

Both versions are undefined behaviour, because you return an address of a locally allocated variable (c), which is technically an address on the stack. It is not valid any more once the function exits. So the question itself is invalid, the output could as well be "mickey mouse".

edit: More technically, the fact you get the "expected" output is just because printf happens to access the same stack location as your addition function with no cleanup happening in-between. But this is really just "by accident".