+ Reply to Thread
Results 1 to 2 of 2

Thread: Difference between malloc and calloc

  1. #1
    Surfer is offline Senior Member
    Join Date
    Mar 2010
    Posts
    321

    Difference between malloc and calloc

    What is the difference between malloc and calloc? Which one we prefer to use and why ?

  2. #2
    Pradeep Panwar is offline Junior Member
    Join Date
    Nov 2010
    Posts
    4
    Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slightly different from the other. malloc() takes a size and returns a pointer to a chunk of memory at least that big:
    void *malloc( size_t size );
    calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk of memory at least big enough to hold them all:
    void *calloc( size_t numElements, size_t sizeOfElement );
    There’s one major difference and one minor difference between the two functions. The major difference is that malloc() doesn’t initialize the allocated memory. The first time malloc() gives you a particular chunk of memory, the memory might be full of zeros. If memory has been allocated, freed, and reallocated, it probably has whatever junk was left in it. That means, unfortunately, that a program might run in simple cases (when memory is never reallocated) but break when used harder (and when memory is reused). calloc() fills the allocated memory with all zero bits. That means that anything there you’re going to use as a char or an int of any length, signed or unsigned, is guaranteed to be zero. Anything you’re going to use as a pointer is set to all zero bits. That’s usually a null pointer, but it’s not guaranteed.Anything you’re going to use as a float or double is set to all zero bits; that’s a floating-point zero on some types of machines, but not on all.
    The minor difference between the two is that calloc() returns an array of objects; malloc() returns one object. Some people use calloc() to make clear that they want an array.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Replies: 2
    Last Post: 1st July 2010, 00:48
  2. Can you point out some differences between new & malloc?
    By TopGun in forum C++ Fundamentals
    Replies: 0
    Last Post: 5th June 2008, 15:09
  3. Implement Malloc and Free function
    By TopGun in forum Microsoft
    Replies: 0
    Last Post: 2nd June 2008, 15:25

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts