Search code examples
cdynamic-memory-allocation

What are all the ways to allocate memory in C and how do they differ?


I'm aware of the following:

  • malloc
  • calloc
  • realloc

What are the differences between these? Why does malloc seem to be used almost exclusively? Are there behavioral differences between compilers?


Solution

  • 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.