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

(Romina) #1
{
smallest = randomNums[i];
}
}
average = ((float)total)/((float)aSize);
printf("The biggest random number is %d.\n", biggest);
printf("The smallest random number is %d.\n", smallest);
printf("The average of the random numbers is %.2f.\n", average);
// When you use malloc, remember to then use free
free(randomNums);
return(0);
}

This program has a minimum of user interaction and looks only for the number of random numbers to
create. It’s an excellent way to test how much memory is on your computer by vastly increasing the
size of your random number array. I was able to create an array of 12 million elements without
triggering the malloc failure section. In fact, when writing this program originally, my total
variable failed before the malloc did. total was originally an int, and when I set the array to 10
million values, the sum total of the random numbers was bigger than the allowed maximum for an
int variable. My average calculation was thus wrong. (It seemed wrong—after all, how could the
average of numbers between 1 and 500 be –167!) When that variable was increased to a double, I
was able to build even bigger arrays of random numbers.


Another interesting fact is that, with a small number of elements, your largest, smallest, and average
numbers can fluctuate, but the more elements are in your array, the more likely you will get a small of
1, a big of 500, and an average right in the middle.


The Absolute Minimum
malloc() allocates heap memory for your programs. You access that heap via a
pointer variable, and you can then get to the rest of the allocated memory using array
notation based on the pointer assigned by the malloc(). When you are done with
heap memory, deallocate that memory with the free() function. free() tosses the
memory back to the heap so other tasks can use it. Key concepts in this chapter include:


  • Use malloc() and free() to allocate and release heap memory.

  • Tell malloc() exactly how large each allocation must be by using the
    sizeof() operator inside malloc()’s parentheses.

  • Allocate only the pointer variables at the top of your function along with the other
    variables. Put the data itself on the heap when you need data values other than
    simple loop counters and totals.

  • If you must track several chunks of heap memory, use an array of pointers. Each
    array element can point to a different amount of heap space.

  • Check to make sure malloc() worked properly. malloc() returns a 0 if the
    allocation fails.

Free download pdf