Background:
Stack memory is present in all major architectures. In the C language, automatic (local) variables are placed on the stack, providing high speed for allocation and deallocation compared to dynamic heap.
Issue:
Stack usage is limited in size, automatic variables are automatically destroyed when leaving the block, and exceeding the stack limits (stack overflow) can lead to program crashes or data corruption.
Solution:
Local variables declared within functions without a special modifier are placed on the stack. This area of automatic storage is created when entering the function and destroyed when exiting. The stack size is limited and can only be changed through linker/system options.
Code example:
#include <stdio.h> void foo() { int arr[100]; // allocated on the stack for (int i = 0; i < 100; ++i) arr[i] = i; printf("First element: %d\n", arr[0]); } // arr is destroyed after exiting foo
Key features:
Can a local variable be returned from a function by address?
No, because the variable is destroyed after exiting the function, and the resulting "dangling pointer" leads to undefined behavior.
int* bad() { int x = 42; return &x; // error: returned pointer points to freed stack }
Is it possible to allocate a large array (e.g., 1 MB) on the stack?
For most systems, stack size is limited (from tens to hundreds of KB). Attempting to declare huge arrays on the stack will lead to stack overflow.
What is the difference between static and automatic variables in allocation?
Static variables (even within a function) are placed in static memory area, are not cleaned between calls, while automatic ones are on the stack and are destroyed upon exiting the block.
In a function for calculations, an array of 8192*1024 doubles was allocated on the stack. The program received SIGSEGV upon launch in Linux, although it compiled without errors.
Pros:
Cons:
For working with large buffers, dynamic memory allocation via malloc/free was used. Only small working variables were placed on the stack.
Pros:
Cons: