This chapter describes the C/C++ dynamic allocation functions. At their core are malloc( ) and free( ). Each time malloc( ) is called, a portion of the remaining free memory is allocated. Each time free( ) is called, memory is returned to the system. The region of free memory from which memory is allocated is called the heap. For a C program, the prototypes for the dynamic allocation functions are in <stdlib.h>. For C++, the header is <cstdlib>. For ease of discussion, this chapter will use the C header name, but references to <stdlib.h> also apply to <cstdlib>.

All C/C++ compilers will include at least these four dynamic allocation functions: calloc( ), malloc( ), free( ), realloc( ). However, your compiler will almost certainly contain several variants on these functions to accommodate various options and environmental differences. You will want to refer to your compiler’s documentation.

While C++ supports the dynamic allocation functions described here, you will typically not use them in a C++ program. The reason for this is that C++ provides dynamic allocation operators called new and delete. There are several advantages to using C++’s dynamic allocation operators. First, new automatically allocates the correct amount of memory for the type of data being allocated. Second, it returns the correct type of pointer to that memory. Third, both new and delete can be overloaded. Since new and delete have advantages over the dynamic allocation functions, their use
is recommended for C++ programs. (For a discussion of new and delete, see Chapter 5.)

C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539 © 2008-2017.
If you may any questions please contact us: