function allocates heap memory, and the free() function deallocates heap memory.
Tip
Be sure to include the stdlib.h header file in all the programs you write that use
malloc() and free().
We might as well get to the rough part. malloc() is not the most user-friendly function for
newcomers to understand. Perhaps looking at an example of malloc() is the best place to start.
Suppose you were writing a temperature-averaging program for a local weather forecaster. The more
temperature readings the user enters, the more accurate the correct prediction will be. You decide that
you will allocate 10 integers to hold the first 10 temperature readings. If the user wants to enter more,
your program can allocate another batch of 10, and so on.
You first need a pointer to the 10 heap values. The values are integers, so you need an integer pointer.
You need to define the integer pointer like this:
Click here to view code image
int * temps; /* Will point to the first heap value */
Here is how you can allocate 10 integers on the heap using malloc():
Click here to view code image
temps = (int *) malloc(10 * sizeof(int)); /* Yikes! */
That’s a lot of code just to get 10 integers. The line is actually fairly easy to understand when you see
it broken into pieces. The malloc() function requires only a single value: the number of bytes you
want allocated. Therefore, if you wanted 10 bytes, you could do this:
malloc(10);
The problem is that the previous description required not 10 bytes, but 10 integers. How many bytes
of memory do 10 integers require? 10? 20? The answer, of course, is that it depends. Only
sizeof() knows for sure.
Therefore, if you want 10 integers allocated, you must tell malloc() that you want 10 sets of bytes
allocated, with each set of bytes being enough for an integer. Therefore, the previous line included the
following malloc() function call:
malloc(10 * sizeof(int))
This part of the statement told malloc() to allocate, or set aside, 10 contiguous integer locations on
the heap. In a way, the computer puts a fence around those 10 integer locations so that subsequent
malloc() calls do not intrude on this allocated memory. Now that you’ve mastered that last half of
the malloc() statement, there’s not much left to understand. The first part of malloc() is fairly
easy.
malloc() always performs the following two steps (assuming that enough heap memory exists to