Automatic storage
- C course
- Beginner
- Lesson 101/116
- 5 min
Learn automatic storage duration (local variables).
Automatic storage
Variables declared inside a function have automatic storage. They live on the stack and disappear when the function returns.
void show(void) {
int x = 42; /* automatic */
printf("%d\n", x);
}Here x is recreated at each call; its memory is given back when the call ends. This needs no free; C cleans it for you. Automatic storage is the simplest approach for most local variables.
Limits of automatic storage
Automatic storage has a limit: when the function returns, the variable is gone. So you cannot return the address of a local array.
int *bad(void) {
int x = 5;
return &x; /* dangerous */
}Here x is deleted when the function returns; the returned address is no longer valid. For large or long-lived memory you should use malloc. For small temporary data, automatic storage is always the best choice.
Practice Print with the show function
Define void show(void) with int x = 42 inside and print x with printf. In main call show.
Starter code
#include <stdio.h>
// Define the show function; assign an integer inside; print with printf
int main(void) {
// Call the show function
return 0;
}Sample solution
void show(void) {
int x = 42;
printf("%d\n", x);
}
show();Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match storage class to property
| Term | Meaning |
|---|---|
automatic |
Gone when function ends |
stack |
Local variables |
no free needed |
Automatic cleanup |
each call |
Recreated |
2 Which is true about automatic storage?
- It is memory allocated with malloc
- It is the storage of local variables Correct answer
- It lives for the whole program
- It is released with free
Explanation: Automatic storage is for local variables.
3 Fill in the blank: function definition
____ show(void) {
int x = 42;
}
void show(void) {
int x = 42;
}
Explanation: void show(void) declares a function with no return value.