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

前端 未结 2 1949
南笙
南笙 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: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 ;
    }
    

提交回复
热议问题