9 - DYNAMIC STORAGE
Published online by Cambridge University Press: 14 January 2010
Summary
This chapter explains the shortcomings of arrays having pre-determined length and the consequent need for dynamic storage. The use of library functions for allocating and freeing memory is then explained.
The concept of a linked list is introduced with particular reference to stacks. The concept is then extended to cover rings and binary trees.
Examples in this chapter include a program for demonstrating ring structures and a program for finding the shortest route through a road network. Finally there is a sorting program based on the monkey puzzle technique.
MEMORY ALLOCATION
The trouble with arrays is that the processor has to be told what space to allocate to each of them before execution starts. There are many applications for which it is impossible to know the detailed memory requirements in advance. What we need is a scheme in which the processor allocates memory during execution and on demand. A program written to use such a scheme fails only if demands on total memory exceed supply, not if one of many individual arrays exceeds its bounds.
The scheme is called ‘dynamic storage.’ For practical purposes it is based on structures. When the program needs a new structure it creates one from a ‘heap’ of unstructured memory. When a program has finished with a structure it frees the memory from which that structure was built, tossing it back on the heap.
- Type
- Chapter
- Information
- Illustrating C , pp. 143 - 162Publisher: Cambridge University PressPrint publication year: 1994