ABSTRACT

In the previous chapters we described two common ways to allocate memory. The first is static allocation. The advantage of static allocation is that there can be no memory leaks; however, the size of the array must be known at the time when the program is written. For example

int arr [100];1

This creates an array with 100 elements. In many cases, the size is unknown when the program is compiled; however, it is known

after the program starts executing. This is the second scenario. An example is shown below, where the size is given by the user:

int * arr2;1 int length;2 printf("Please enter the length of the array: ");3

scanf("%d", & length);4

arr2 = malloc(length * s i z eo f ( int ));5

This scenario is often used when reading data from a file. One common strategy is to: 1. Read the file once to determine how much memory is needed. 2. Allocate the required memory. 3. Call fseek to return to the beginning of the file. 4. Read the file again and store the data in the allocated memory. This chapter describes how to handle another common scenario: when it is impractical

or impossible to know the size even after the program starts. Memory must be allocated and released on an as-needed basis. This is a very common scenario.