Click here to Skip to main content
15,911,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, Can any one help me.

what is the difference between malloc() and calloc()?
Explain in deep manner.
Posted

malloc is the workhorse for memory allocation (calloc itself uses malloc).
You may find yourself the differences between the two functions just having a look at the following MSDN pages:
malloc[^], calloc[^].
:)
 
Share this answer
 
Comments
project.gearup 14-Sep-10 6:58am    
please avoid giving links if you know the concept you can very well explain it else let others to explain.
CPallini 14-Sep-10 8:06am    
What's wrong with links? I leave MSDN to explain (and it explain all the details).
ganeshkawade2003 24-Sep-10 8:33am    
I guess ders nothing wrong with providing links, showing a proper direction is always good.
The allocated memory supplied by calloc is zero initialised, whereas that allocated by malloc just contains whatever junk was in their before.

Also calloc takes 2 arguments one for the number of objects and one for the size of an object, whereas malloc takes just the number of bytes to be allocated. I believe memory allocated by calloc can be slightly larger than expected as the objects can be aligned to any relevant platform boundaries. The intention is for calloc to be used if items are to accessed as an array.

Hope that helps,
Charles Keepax
 
Share this answer
 
The function void* malloc(size_t size) is used to allocate size number of bytes.
It returns a pointer to the allocated block.

The function void* calloc(size_t nelement, size_t elementSize) allocates enough memory to store a total of nelement elements of size elementSize. You'd use this to allocate a known number of elements, such as allocating 10 my_structs:

struct my_struct
{
    int x;
    int y;
}

...

my_struct* = calloc(10, sizeof(my_struct);


It's explained in more detail here[^]

The memory is also initialized when using calloc.

Hope this helps,
Fredrik
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900