Why reverse the order of printf() gives different output?

前端 未结 2 1925
南笙
南笙 2021-01-29 12:09
#include 
int ∗addition(int a, int b){
    int c = a + b ;
    int ∗d = &c ;
    return d ;
}

int main (void) {
   int result = ∗(addition(1, 2));
           


        
相关标签:
2条回答
  • 2021-01-29 12:33

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

    0 讨论(0)
  • 2021-01-29 12:44

    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 ;
    }
    
    0 讨论(0)
提交回复
热议问题