Reputation: 4364
Is the following program correct? I return the local variable x
from function fun
and use it in the calling function. Can anyone explain if there is anything wrong with returning a local variable even if it contains the valid address in main
?
#include <stdio.h>
int fun(int j) {
int x = j;
return x;
}
int main() {
printf("%d\n", fun(1));
// OR
int k = 9;
printf("%d\n", fun(k));
// OR
printf("%d\n", fun(&k));
return 0;
}
If my code is wrong then why is it?
Upvotes: 2
Views: 71
Reputation: 144800
It is OK in C for a function to return the value of a local object. The compiler generates code to copy this value to the object into which the function return value is stored or used in an expression. The local object can be a scalar or a structure alike.
Conversely, returning a pointer to a local object is not OK because the object pointed to will have gone out of scope by the time the pointer is dereferenced by the caller.
#include <stdio.h>
int good(int j) {
int x = j;
return x; // OK
}
int *bad(int j) {
int x = j;
return &x; // NOT OK
}
int main() {
printf("%d\n", good(1)); // prints 1
int k = 9;
printf("%d\n", good(k)); // prints 9
printf("%d\n", *bad(1)); // undefined behavior
return 0;
}
The posted code in incorrect here: printf("%d\n", fun(&k));
because fun
expects an int
argument, not a pointer to int
.
Upvotes: 3