int numbers*;
numbers = malloc ( sizeof(int) * 10 );
I want to know how is this dynamic memory allocation, if I can store just 10 int
items to the memory block ? I could just use the array and store elemets dynamically using index. Why is the above approach better ?
I am new to C, and this is my 2nd day and I may sound stupid, so please bear with me.
The main reason why
malloc()
is useful is not because the size of the array can be determined at runtime - modern versions of C allow that with normal arrays too. There are two reasons:malloc()
have flexible lifetimes;That is, you get runtime control over when to create the object, and when to destroy it. The array allocated with
malloc()
exists from the time of themalloc()
call until the correspondingfree()
call; in contrast, declared arrays either exist until the function they're declared in exits, or until the program finishes.malloc()
reports failure, allowing the program to handle it in a graceful way.On a failure to allocate the requested memory,
malloc()
can returnNULL
, which allows your program to detect and handle the condition. There is no such mechanism for declared arrays - on a failure to allocate sufficient space, either the program crashes at runtime, or fails to load altogether.