I'm aware of the following:
What are the differences between these? Why does malloc seem to be used almost exclusively? Are there behavioral differences between compilers?
There are two types of memory allocations: Compile-time or Static Memory Allocation. Run-time or Dynamic Memory Allocation.
There are two types of memory allocations. Static and dynamic.
C malloc() method The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.
malloc
allocates memory. The contents of the memory are left as-is (filled with whatever was there before).
calloc
allocates memory and sets its contents to all-zeros.
realloc
changes the size of an existing allocated block of memory, or copies the contents of an existing block of memory into a newly allocated block of the requested size, and then deallocates the old block.
Obviously, realloc
is a special-case situation. If you don't have an old block of memory to resize (or copy and deallocate), there's no reason to use it. The reason that malloc
is normally used instead of calloc
is because there is a run-time cost for setting the memory to all-zeros and if you're planning to immediately fill the memory with useful data (as is common), there's no point in zeroing it out first.
These functions are all standard and behave reliably across compilers.
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