Question and Answer
Sun, 10/03/2013 - 8:39pmQ Why do you need to allocate memory at runtime?
Q Why do you need to allocate memory at runtime?
The realloc() Function
The realloc() function gives you a means to change the size of a piece of memory space allocated by the malloc() function, the calloc() function, or even itself.
The syntax for the realloc() function is
#include <stdlib.h>
void *realloc(void *block, size_t size);
Here block is the pointer to the start of a piece of memory space previously allocated. size specifies the total byte number you want to change to. The realloc() function returns a void pointer.
The calloc() Function
Besides the malloc() function, you can also use the calloc() function to allocate a memory storage dynamically. The differences between the two functions are that the latter takes two arguments and that the memory space allocated by calloc() is always initialized to 0. There is no such guarantee that the memory space allocated by malloc() is initialized to 0.
The syntax for the calloc() function is
#include <stdlib.h>
void *calloc(size_t nitem, size_t size);
Releasing Allocated Memory with free()
Because memory is a limited resource, you should allocate an exactly sized piece of memory right before you need it, and release it as soon as you don’t need it.
The program in Listing 17.2 demonstrates how to release allocated memory by calling the free() function.
TYPE
Listing 17.2. Using the free() and malloc() functions together.
Allocating Memory at Runtime
There are many cases when you do not know the exact sizes of arrays used in your programs, until much later when your programs are actually being executed. You can specify the sizes of arrays in advance, but the arrays can be too small or too big if the numbers of data items you want to put into the arrays change dramatically at runtime.
To help solidify your understanding of this hour’s lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the Workshop before you move to the next lesson. The answers and hints to the questions and exercises are given in Appendix E, “Answers to Quiz Questions and Exercises.”