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).
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.
If you cannot see this codecast, please click here.
Aside:Video Description.
Check Your UnderstandingCheck 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?