Previous: 14.1 Storage Classes
Up: 14 Storage Class and Scope
Next: 14.3 Pointers to Functions
Previous Page: 14.1.8 Stack vs Heap Allocation
Next Page: 14.2.1 Library Functions for Dynamic Allocation
In the previous section we have described the the storage classes which determined how memory for variables are allocated by the compiler. When a variable is defined in the source program, the type of the variable determines how much memory the compiler allocates. When the program executes, the variable consumes this amount of memory regardless of whether the program actually uses the memory allocated. This is particularly true for arrays. However, in many problems, it is not clear at the outset how much memory the program will actually need. Up to now, we have declared arrays to be ``large enough'' to hold the maximum number of elements we expect our application to handle. If too much memory is allocated and then not used, there is a waste of memory. If not enough memory is allocated, the program is not able to handle the input data.
We can make our program more flexible if, during execution, it could allocate additional memory when needed and free memory when not needed. Allocation of memory during execution is called dynamic memory allocation. C provides library functions to allocate and free memory dynamically during program execution. Dynamic memory is allocated on the heap by the system.
It is important to realize that dynamic memory allocation also has limits. If memory is repeatedly allocated, eventually the system will run out of memory.