C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

When you’re done with the heap memory, give it back to the system. Use free() to do that.
free() is a lot easier than malloc(). To free the 10 integers allocated with the previous
malloc(), use free() in the following manner:


Click here to view code image


free(temps); /* Gives the memory back to the heap */

If you originally allocated 10 values, 10 are freed. If the malloc() that allocated memory for temps
had allocated 1,000 values, all 1,000 would be freed. After freeing the memory, you can’t get it back.
Remember, free() tosses the allocated memory back onto the heap of memory—and after it’s
tossed, another task might grab the memory (remember the dirt heap analogy). If you use temps after
the previous free(), you run the risk of overwriting memory and possibly locking up your
computer, requiring a reboot.


If you fail to free allocated memory, your operating system reclaims that memory when your program
ends. However, forgetting to call free() defeats the purpose of using heap memory in the first
place. The goal of the heap is to give your program the opportunity to allocate memory at the point the
memory is needed and deallocate that memory when you’re finished with it.


Multiple Allocations


An array of pointers often helps you allocate many different sets of heap memory. Going back to the
weather forecaster’s problem, suppose the forecaster wanted to enter historical temperature readings
for several different cities. But the forecaster has a different number of readings for each different
city.


An array of pointers is useful for such a problem. Here is how you could allocate an array of 50
pointers:


Click here to view code image


int * temps[50]; /* 50 integer pointers */

The array will not hold 50 integers (because of the dereferencing operator in the definition); instead,
the array holds 50 pointers. The first pointer is called temps[0], the second pointer is temps[1],
and so on. Each of the array elements (each pointer) can point to a different set of allocated heap
memory. Therefore, even though the 50 pointer array elements must be defined for all of main(),
you can allocate and free the data pointed to as you need extra memory.


Consider the following section of code that the forecaster might use:


Click here to view code image


for (ctr = 0; ctr < 50; ctr++)
{
puts("How many readings for the city?")
scanf(" %d", &num);
// Allocate that many heap values
temps[ctr] = (int *)malloc(num * sizeof(int));
// This next section of code would ask for each temperature
// reading for the city
}
Free download pdf