In our lecture we had the following example:
int *foo(int x) {
return &x;
}
int* pt = foo(x);
*pt = 17;
It was shown as a bad example, but not further explained. Why is this bad?
In our lecture we had the following example:
int *foo(int x) {
return &x;
}
int* pt = foo(x);
*pt = 17;
It was shown as a bad example, but not further explained. Why is this bad?
Bad thing is that you are returning a pointer to an automatic local variable. It will no longer be exist once function returns and then the statement *pt = 17; will cause program to behave erratically.
A pointer to static local variable can be returned.
int *foo() {
static int x;
return &x;
}
int* pt = foo();
*pt = 17;
In foo the variable x is local hence it ceases to exist after the method exits. When a function returns, its automatic, local variables are discarded, so the returned pointer in this case is invalid (it points to an array that no longer exists).
int* pt = foo(x);
*pt = 17;
Hence, now access to pt results in Undefined Behavior. You should malloc it instead:
int *foo()
{
int *x = malloc(sizeof(int));
*x = 0;
return x;
}
int* pt = foo();
*pt = 17;
free(pt);
Here
int *foo(int x) {
x is a local, non-static variable. By doing
return &x;
you return the address of the local variable x. It exists as long as the function does , and when the function exits, this address will be invalid for you to play with. By using
*pt = 17;
you dereference this address and write 17 to this invalid memory location. This triggers Undefined Behavior. This is why the given code is bad.