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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With