In what situation am I supposed to use malloc? I'm confused by when dynamic allocation should be used in C-Collection of common programming errors
Here’s a archetypal example of the need for dynamic allocation: Making a dynamic container. Since you don’t know the number of elements in advance, each element has to be allocated dynamically. Since you populate the container in a loop, each element must outlive the loop scope. This is the “zero-one-many” rule at its barest, and the “many” part of it immediately entails dynamic allocation:
int value;
node * my_list = NULL;
while (get_one_more_input(&value) == SUCCESS)
{
node * elem = malloc(sizeof(node));
elem->data = value;
elem->next = my_list;
my_list = elem;
}
The crux here is that the actual list node is only populated inside the loop which reads the input data, but clearly it must outlive that scope. Thus no automatic object can do, because it would only live to the end of the scope, and also no static element could do, because you cannot know the number of loop iterations beforehand. Dynamic lifetime and storage management is the only solution here, and that’s what it is primarily intended for.
In C you will be doing a lot of this by hand, since dynamic data structures are at the very heart of computing. C++ makes a lot of this much easier and safer by wrapping all the dynamic management logic into hidden-away, reusable code that you never need to look at as a consumer (though it’s still doing the exact same thing).