Advanced Use of Pointers
Dynamic Storage Allocation:
Many programs require dynamic storage allocation; the ability to allocate
storage as needed during program execution. Dynamically allocated storage may be
used for any kind of data object. The objects most commonly allocated are arrays,
strings and structures.
The malloc() Function:
The most important storage allocation function in C is named malloc().
When called malloc allocates a block of size bytes and returns a pointer to it:
void *malloc(size_t size);
malloc returns a "generic" pointer (pointer to void)
that can be typecast into a pointer to an object of any type.
Memory allocated by malloc is not cleared or otherwise initialized.
To determine how much storage to allocate for an object we can use the sizeof
operator, which can be applied to an expression or a type. If we want to allocate storage
for a double value we could say:
ptr = (double *) malloc(sizeof double);
The "generic" pointer returned by malloc is typecast into the correct
type pointer (a pointer to a double, in this case). While this is not
necessary in C it is good programming practice.
If a memory block of the requested size is not available malloc will
return a null pointer, that is, a pointer with a value of zero.
The calloc() Function
Another function you can use to dynamically allocate memory is calloc:
void *calloc(size_t n, size_t size);
Use calloc to allocate memory for arrays. You can allocate memory for
an array of n items of size size each. For example, to dynamically
allocate memory for an array of 16 doubles:
ptr = (double *) calloc( 16, sizeof double);
Unlike malloc, calloc will set all bytes allocated to zero.
The free() Function:
The free() function releases a block of memory which was allocated by malloc or calloc:
void free(void *ptr);
You should always free any memory you allocate using malloc or calloc.
Failure to do so can result in out of memory errors and/or "memory leaks."
At the least this can cause your system to slow down due to disk caching of memory.
At the worst it can cause system crashes due to running out of memory.