#include<iostream>
int* function() {
int a = 2;
return &a;
}
int main() {
int* b = function();
*b = 3;
return 0;
}
I was trying to run this program, but this is supposed to give me an error because a
should be deleted after leaving the function. However, I received no error in Visual Studio 2022. a
is not even a static variable, nor is b
constant.
I tried to copy and paste this code in different compilers to see if the lecture was wrong, but I recieved
main.cpp:4:16: warning: address of local variable ‘a’ returned [-Wreturn-local-addr]
like what it is supposed to be.
3
Answers
There are two possible causes:
You are returning a local variable’s address, which will cause undefined behavior for
a
is no longer available(or, lifetime is over) after return.To return
a
, you should declarea
as a pointer and allocate memory for it.This should work fine.
The compiler will only point out your problem with a warning, but it will not throw an error. You can see that compiler wants to tell you in
-Wreturn-local-addr
.The function returns
&a
, and sincea
goes out of scope after the function returns (asa
is declared on the stack),&a
is dangling. The compiler sees this and warns you about that, but it doesn’t error since there technically isn’t anything wrong with returning an pointer, just as there isn’t an issue with returningnullptr
.BTW: "Errors" and "warnings" in C++ are completely different things. Errors cause compilation to fail (such as syntax errors), while warnings notify you about potential fail points but allow the code to compile.