Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 953
Firoso Avatar asked Sep 24 '10 21:09

Firoso


People also ask

What are the different types of memory allocation in C?

There are two types of memory allocations: Compile-time or Static Memory Allocation. Run-time or Dynamic Memory Allocation.

What are the different types of memory allocations?

There are two types of memory allocations. Static and dynamic.

How do you allocate memory in C?

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.


1 Answers

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.

like image 62
Tyler McHenry Avatar answered Sep 18 '22 17:09

Tyler McHenry