Can memory of a local variable be accessible outside its scope?
Hi everyone! I just started learning C++ and encountered some confusing behavior. I wrote a function that returns a pointer to a local variable:\n\n```cpp\nint* getPointer() {\n int x = 42;\n return &x;\n}\n\nint main() {\n int* ptr = getPointer();\n std::cout << *ptr << std::endl; // Prints 42\n // ... later ...\n std::cout << *ptr << std::endl; // May print garbage\n}\n```\n\nThe first output works — I get 42. But I read that you shouldn't do this because x is a local variable and its memory is freed after exiting the function. However, the code compiles and works! Why? And what actually happens to the memory? Does the compiler somehow preserve the value, or is it just luck? How should I properly return data from a function if I need to return a pointer?
No answers yet.
Log in to leave an answer