I don't know why this works. Since x is a local variable, I thought I would get an error when I try to return it. However, The first printf works fine, but then it just prints out 0. Can anyone explain what's going on here?
#include <stdio.h>
int* func1() {
int x = 123123;
int *y = &x;
return y;
}
int main()
{
int* c = func1();
printf("%d\n", *c); // output: 123123
printf("%d\n", *c); // output: 0
return 0;
}
The return statement should not return a pointer that has the address of a local variable ( sum ) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.
Because it will cause undefined behavior in your program. Show activity on this post. If you return a pointer to a local variable once the function returns it is out of scope. From then on it is undefined behavior if you access the returned pointer.
And in function max() , the returned variable is a pointer which is created inside the function. In my opinion, returning a local pointer is not allowed in c/c++.
Return Function Pointer From Function: To return a function pointer from a function, the return type of function should be a pointer to another function. But the compiler doesn't accept such a return type for a function, so we need to define a type that represents that particular function pointer.
The following happens:
func1
, you created the local x
variable and initialised it with a value, i.e. x
is on the stack now.x
and return it to main
.func1
and its variables x
(and, irrelevant to the question, y
) are free
d, or popped off the stack, i.e. their memory locations are not reserved any more to hold their values. After this, any other part of the program is allowed to use the memory space that was allocated for x
within func1
, as func1
isn't active any more.printf
call still happens to see the old value of the memory location where x
used to be (but this is not guaranteed) andprintf
call makes it apparent that something else (with the value of 0, such as the first printf
's return value as described by R. Joiny) is (or was) using the same address as x
within func1
.This article of the C Programming Boot Camp pretty much describes your situation:
A key to understanding the stack is the notion that when a function exits, all of its variables are popped off of the stack (and hence lost forever). Thus stack variables are local in nature. This is related to a concept we saw earlier known as variable scope, or local vs global variables. A common bug in C programming is attempting to access a variable that was created on the stack inside some function, from a place in your program outside of that function (i.e. after that function has exited).
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