Is this code is completely valid? Will returning a pointer here will not throw us to undefined behavior?
#include <iostream>
using namespace std;
int* lab(int* i) {
int k=9;
i=&k;
return i;
}
int main(void) {
int* i=0;
cout << *lab(i) << endl;
return 0;
}
EDIT: how valid code can look like?
No sir. That is not valid. You can’t return a pointer to a local variable. Once
lab()exitskdoes not exist and dereferencing a pointer to it causes undefined behavior.Think about where
kis stored. Automatic variables that you take the address of are stored on the stack. The stack grows when functions are entered and shrinks when they exit. Whenlab()returns the stack space that was allocated tokis reclaimed and can be reused by the runtime, possibly for other local variables in some other functions.There are a couple of ways to fix this. The easiest is to have the caller provide a location to store the value in rather than having
lab()try to find space. This eliminates the problem ofkbeing deallocated whenlab()returns.Another way is to declare
kasstatic. Static variables are stored in permanent storage somewhere, not on the stack, so their addresses remain valid throughout the lifetime of the program.And yet another way is to allocate memory on the heap using
new.