Programming in C

(Barry) #1

384 Chapter 17 Miscellaneous and Advanced Features


It is frequently desirable, if not necessary, to be able to dynamicallyallocate storage
while a program is running. Suppose you have a program that is designed to read in a set
of data from a file into an array in memory. Suppose, however, that you don’t know how
much data is in the file until the program starts execution.You have three choices:
n Define the array to contain the maximum number of possible elements at compile
time.
n Use a variable-length array to dimension the size of the array at runtime.
n Allocate the array dynamically using one of C’s memory allocation routines.

Using the first approach, you have to define your array to contain the maximum number
of elements that would be read into the array, as in the following:
#define kMaxElements 1000

struct dataEntry dataArray [kMaxElements];
Now, as long as the data file contains 1,000 elements or less, you’re in business. But if the
number of elements exceeds this amount, you must go back to the program, change the
val ue of kMaxElements, and recompile it. Of course, no matter what value you select,
you always have the chance of running into the same problem again in the future.
With the second approach, if you can determine the number of elements you need
before you start reading in the data (perhaps from the size of the file, for example), you
can then define a variable-length array as follows:
struct dateEntry dataArray [dataItems];
Here, it is assumed that the variable dataItemscontains the aforementioned number of
data items to read in.
Using the dynamic memory allocation functions, you can get storage as you need it.
That is, this approach also enables you to allocate memory as the program is executing.
To use dynamic memory allocation, you must first learn about three functions and one
new operator.

The callocand mallocFunctions


In the standard C library, two functions, called callocand malloc, can be used to allo-
cate memory at runtime.The callocfunction takes two arguments that specify the
number of elements to be reserved and the size of each element in bytes.The function
returns a pointer to the beginning of the allocated storage area in memory.The storage
area is also automatically set to 0.
callocreturns a pointer to void, which is C’s generic pointer type. Before storing
this returned pointer inside a pointer variable in your program, it can be converted into
a pointer of the appropriate type using the type cast operator.
The mallocfunction works similarly, except that it only takes a single argument—the
total number of bytes of storage to allocate—and also doesn’t automatically set the stor-
age area to 0.
Free download pdf