-2
#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 ∗resultptr = addition(1, 2);

   printf(”result = %d\n”, ∗resultptr);
   printf(”result = %d\n”, result);
   return 0 ;
}

This will give the correct answer. But it's strange that once I have interchanged the order of the last two printf()s, abnormal answer will be given.

printf(”result = %d\n”, result);
printf(”result = %d\n”, ∗resultptr);

Why is that? Is it because some internal implementations of printf()?

I have opened the -Wall option but no warning displayed.

Thank you for your answers! It's the first question for me on stackoverflow.

But why reverse the order will give different answers? If it's due to the undefined behavior of returning an local variable, why the first program gives the correct answer but the second can't, while the only difference is the order of printf()?

  • Yes, because by returning the address of a local variable, and using it after function returns, you are going into the realm of undefined behaviour. And no, its not because of internal implementation of printf. – UltraInstinct Sep 01 '14 at 06:28
  • 2
    Please turn on, read, and understand compiler warnings. – Ken Y-N Sep 01 '14 at 06:28
  • possible duplicate of [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope). Focused on C++, but the same applies in C. – juanchopanza Sep 01 '14 at 06:30
  • possible duplicate of [Returning local variables in C++ (Rule 21 in Effective C++, 3rd edition)](http://stackoverflow.com/questions/24789982/returning-local-variables-in-c-rule-21-in-effective-c-3rd-edition) – Ken Y-N Sep 01 '14 at 06:31
  • In my computer, your code can be compiled by `gcc -o main main.c` and give the answer "result = 3" and "*resultptr = -2" whether interchange the order of the last two `printf()` or not. So, i think it's up to the compiler. – Anthony Cooper Sep 01 '14 at 06:47

2 Answers2

5

In this function,

int ∗addition(int a, int b){
    int c = a + b ;   // Object on the stack
    int ∗d = &c ;     // d points to an object on the stack.
    return d ;
}

you are returning a pointer to an object from the stack. The returned memory is invalid after you return from the function. Accessing that memory leads to undefined behavior.

If you change the function to return an int, things would be OK.

int addition(int a, int b){
    return (a + b);
}

int main (void) {
   int result1 = addition(1, 2);
   int result2 = addition(2, 3);

   printf(”result = %d\n”, result1);
   printf(”result = %d\n”, result2);
   return 0 ;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
4

You're returning a pointer to a local variable, which gets deallocated after the function exits (and thus invokes undefined behavior).

IllusiveBrian
  • 3,105
  • 2
  • 14
  • 17