Malloc is used for dynamic memory allocation and is useful when you don't know the amount of memory needed during compile time. Allocating memory allows objects to exist beyond the scope of the current block.
The malloc() is used to allocate a single block of memory, calloc() is used to allocate multiple blocks of memory, and realloc()is used to reallocate memory that is allocated to malloc() or calloc() functions.
C realloc() method “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.
If you need to keep your data, use realloc(). It's ~4 times faster than using malloc()/free() and copying your data when scaling up. When scaling down it is 10,000-100,000 times faster.
From Open Groups' specifications:
If ptr is a null pointer, realloc() shall be equivalent to malloc() for the specified size.
If ptr does not match a pointer returned earlier by calloc(), malloc(), or realloc() or if the space has previously been deallocated by a call to free() or realloc(), the behavior is undefined.
malloc
is not required, you can use realloc
only.
malloc(n)
is equivalent to realloc(NULL, n)
.
However, it is often clearer to use malloc
instead of special semantics of realloc
. It's not a matter of what works, but not confusing people reading the code.
(Edit: removed mention of realloc
acting as free
, since it's not standard C. See comments.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With