|
2.3 Basic Description of Terms and Functions
2.3.1 General Memory Terms and ConceptsAny program can be divided into 2 logical parts: text and data. Text is the actual program code in machine-readable format and data is the information that the text operates on when it is executing. The data, in turn, can be divided into 3 logical parts according to where it is stored: static, stack, and heap. Static data is the information whose storage space is compiled into the program.
Stack data is data allocated at runtime to hold information used inside of functions. This data is managed by the system in the space called stack space.
Heap data is also allocated at runtime and provides a programmer with dynamic memory capabilities.
It is the heap data that is managed by this library. Although the above is an example of how to use the malloc and free commands, it is not a good example of why using the heap for runtime storage is useful. Consider this: You write a program that reads a file into memory, processes it, and displays results. You would like to handle files with arbitrary size (from 10 bytes to 1.2 megabytes and more). One problem, however, is that the entire file must be in memory at one time to do the calculations. You don't want to have to allocate 1.2 megabytes when you might only be reading in a 10 byte file because it is wasteful of system resources. Also, you are worried that your program might have to handle files of more than 1.2 megabytes. A solution: first checkout the file's size and then, using the heap-allocation routines, get enough storage to read the entire file into memory. The program will only be using the system resources necessary for the job and you will be guaranteed that your program can handle any sized file.
2.3.2 Functionality Supported by All Malloc LibrariesAll malloc libraries support 4 basic memory allocation commands. These
include malloc, calloc, realloc, and free. For
more information about their capabilities, check your system's manual
pages - in unix, do a
WARNING: there is a quite common myth that all of the space that
is returned by malloc libraries has already been cleared. Only
the
This document was generated by Gray Watson on May, 16 2007 using texi2html 1.76.
This work is licensed by Gray Watson
under the Creative Commons
Attribution-Share Alike 3.0 License. |