I’m just reading about malloc() in C.
The Wikipedia article provides an example, however it justs allocate enough memory for an array of 10 ints in comparison with int array[10]. Not very useful.
When would you decided to use malloc() over C handling the memory for you?
Dynamic data structures (lists, trees, etc.) use
mallocto allocate their nodes on the heap. For example:Consider how new data is added to the list with
sl_insert_front. You need to create a node that will hold the data and the pointer to the next node in the list. Where are you going to create it?mallocis used in C to allocate stuff on the heap – memory space that can grow and shrink dynamically at runtime, and the ownership of which is completely under the programmer’s control. There are many more examples where this is useful, but the one I’m showing here is a representative one. Eventually, in complex C programs you’ll find that most of the program’s data is on the heap, accessible through pointers. A correct program always knows which pointer “owns” the data and will carefully clean-up the allocated memory when it’s no longer needed.