Section 21.1 malloc()
- Dynamically Allocating Memory
Dynamic memory allocation happens at runtime: depending on your needs you can ask for memory, which is then reserved in the so-called
heap (as opposed to the
stack, where your ’normal’ variables are stored).
This can be useful, for example, when you need an array to store data but you don’t know until runtime how large this array needs to be.
Recall that memory in the stack is managed for you. The heap is a bit different. Unlike variables in the stack (which only persist for the duration of the function in which they are declared), memory allocated dynamically remains reserved for you until you explicitly
free this reservation.
The C-command to ask for (allocate) memory in the heap is called
malloc()
. This function takes as an argument the amount of space you wish to reserve (in bytes), attempts to find that amount of space in the heap and then returns a pointer to the start of the reserved block of memory. The return data type of the
malloc()
function is a
void *
and it is your job to
cast this void pointer to the type of pointer (
int *
,
float *
, etc.) that fits your needs.
The prototype for
malloc()
is thus
void * mallow(int numb_bytes);
The
malloc()
function can be found in the standard library
<stdlib.h>
. You therefore need to
#include <std lib.h>
in order to use the function. The following video demonstrates the use of
malloc()
.
If you cannot see this codecast, please click here.
Check Your Understanding Check Your Understanding
1.
Suppose you wanted to reserve space in memory for one number of type float and then store the memory location in a variable numptr of type
float *
. Which of the following would be the correct way to do so?
numptr = (float *) malloc(sizeof(float));
Correct
numptr = malloc(float *);
Not quite. Try again!
numptr = (float) malloc(sizeof(float *));
Not quite. Try again!
(float *) numptr = malloc (float);
Not quite. Try again!
numptr = (float *) malloc(sizeof(num));
Not quite. Try again!