Dynamic Memory Allocation
Dynamic Memory Allocation

Up to now, we have been given all the sizes of our arrays in the project specifications. What if you aren't given the size? If you had to aribitraily chose a number, each program would run this risk of not having large enough arrays or making them too large and wasting large amounts of memory.

To fix this problem, C provides function in stdlib.h which allow for the dynamic allocation of memory. The functions studied in this course are:

void *malloc (size_t size); void *calloc (size_t nelem, size_t elsize); From the prototype we can see that malloc() takes a size. This size is found by passing the number of elements required in the array and the sizeof() that datatype. Then a void pointer is returned which the programmer must cast to the type they desire so it can be used as an array.

The difference between malloc() and calloc():

An example using malloc(): #include <stdio.h> #include <stdlib.h> main() { int *intPtr; int num; printf("How many ints would you like to store? "); scanf("%d", &num); intPtr = (int *)malloc(sizeof(int) * num); if(intPtr == NULL) { printf("Memmory Allocation Failed. Program Exiting.\n"); exit(-1); } . . . Don't for get to check for NULL after every memory allocation. If NULL is returned, your memory was not allocated and there is not recovering, so exit the program.

Here are two examples which use malloc() (among other things). The first allocates memory in main(); the second in a function. The programs both preform a search which is similar to Selection Sort. Don't worry about understanding the search, just the memory allocation. *smile*


Main Page