#include
int ∗addition(int a, int b){
int c = a + b ;
int ∗d = &c ;
return d ;
}
int main (void) {
int result = ∗(addition(1, 2));
You're returning a pointer to a local variable, which gets deallocated after the function exits (and thus invokes undefined behavior).
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 ;
}