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

(Romina) #1
Besides defining an array at the top of main(), what have you gained by using
malloc()? For one thing, you can use the malloc() function anywhere in your
program, not just where you define variables and arrays. Therefore, when your
program is ready for 100 double values, you can allocate those 100 double values.
If you used a regular array, you would need a statement like this toward the top of
main():
Click here to view code image
doublemyVals[100]; /* A regular array of 100 doubles */
Those 100 double values would sit around for the life of the program, taking up
memory resources from the rest of the system, even if the program only needed the 100
double values for only a short time. With malloc(), you need to define only the
pointer that points to the top of the allocated memory for the program’s life, not the
entire array.

If There’s Not Enough Heap Memory


In extreme cases, not enough heap memory might exist to satisfy malloc()’s request. The user’s
computer might not have a lot of memory, another task might be using a lot of memory, or your
program might have previously allocated everything already. If malloc() fails, its pointer variable
points to a null value, 0. Therefore, many programmers follow a malloc() with an if, like this:


Click here to view code image


temps = (int *) malloc(10 * sizeof(int));
if (temps == 0)
{
printf("Oops! Not Enough Memory!\n");
exit(1); // Terminate the program early
}
// Rest of program would follow...

If malloc() works, temps contains a valid address that points to the start of the allocated heap. If
malloc() fails, the invalid address of 0 is pointed to (heap memory never begins at address zero)
and the error prints onscreen.


Tip

Programmers often use the not operator, !, instead of testing a value against 0 , as done
here. Therefore, the previous if test would more likely be coded like this:
Click here to view code image
if (!temps) /* Means, if not true */

Freeing Heap Memory

Free download pdf