Verified Jobs Live
C++ and C Medium Level ~3 min read

Why is returning a pointer to a local variable invalid, and what are safer alternatives?

Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Model Answer & Deep-Dive Explanation

An ordinary local variable with automatic storage duration ceases to exist when the function retu s. A pointer to it then dangles, and accessing the former object through that pointer is invalid even if the old bytes seem unchanged. Retu a value when possible, accept caller-provided storage with a clear size contract, or retu an owning object such as std::string or std::vector in C++. In C, document dynamically allocated ownership and the matching deallocator. Static storage changes lifetime but also introduces shared state and concurrency considerations.