In the C language, variables with automatic storage duration (auto, by default) are created on the stack when entering their scope (usually a function) and are automatically destroyed upon exiting it.
The features include:
Example of correct and incorrect usage:
int* wrong() { int x = 42; return &x; // ERROR: x will be destroyed after exiting the function } void correct() { int y = 123; printf("%d\n", y); // all good }
What happens if you return the address of a local variable from a function?
Common incorrect answer: "The pointer will preserve its value."
Correct answer: The returned address will become invalid after exiting the function, and the memory area will be reassigned to other automatic variables or functions. Using such a pointer leads to undefined behavior.
Example:
int* myfunc() { int temp = 10; return &temp; // temp will be destroyed after return } int main() { int* p = myfunc(); printf("%d\n", *p); // UNDEFINED BEHAVIOR }
Story
Story
Story
In the firmware of a medical recorder, caching was implemented on the stack to speed up data processing. Under load, the stack overflowed, causing device resets and loss of patient data.