Difference Between calloc, malloc, and realloc

Question: What is the difference between malloc(), calloc(), and realloc()

malloc, calloc, and realloc are functions used for memory allocation in C/C++ languages. There are some fundamental differences on how the above functions work.
realloc()
First of all realloc() is actually a reallocation function. It is used to resize a previously allocated (using malloc(), calloc(), or realloc()) block of memory to the desired size. Depending on whether the new size if less or more than the original size the block may be moved to new location.

Usage and example of realloc()

Function Prototype for realloc():
void *realloc(void *pointer, size_t size);
  

malloc() vs calloc()


There two basic difference between malloc() and calloc() functions:
1. malloc() allocates memory in bytes. So the programmer specifies how many bytes of memory malloc should allocate and malloc will allocate that many bytes (if possible) and return the address of the newly allocated chunk of memory.
 
Function prototype for malloc():
void *malloc(size_t size); //size is the number of bytes to allocate
 
On the other hand calloc() allocates a chunk of memory specified by a block/element size and the number of blocks/elements. 
Function prototype for calloc():

void *calloc(size_t nelements, size_t elementSize);

2. malloc() does not initialize memory after it allocates it. It just returns the pointer back to the calling code and the calling code is responsible for initialization or resetting of the memory, most probably by using the memset() function. On the other hand calloc() initializes the allocated memory to 0. calloc() is obviously slower than malloc() since it has the overhead of initialization, so it may not be the best way to allocate memory if you don't care about initializing the allocated memory to 0.

Side note: Don't forget to free your allocated memory when you are done with it using the free() function.

15 comments:

  1. Thanks for providing such good info!

    ReplyDelete
  2. good info....
    Prateek Jain

    ReplyDelete
  3. thnx $ ths info.............

    ReplyDelete
  4. Thanks alot .

    ReplyDelete
  5. thanks....

    ReplyDelete
  6. Very clear info, Thanks

    ReplyDelete
  7. Very nicely explained...made it simple to understand. Thanks!!

    ReplyDelete
  8. I didnt get the second difference.. can anyone explain it in more detail???

    ReplyDelete
  9. karthik sridhara11/11/2013 10:45 PM

    Thank you...

    ReplyDelete