Thread: calloc vs malloc

  1. #1
    Registered User
    Join Date
    Nov 2001

    Question calloc vs malloc

    Hey guys, quick question.

    What exactly is the difference(benefit) of using calloc over malloc
    They seem dreadfully similar to me.

    int *p;
    int *q;

    p = (int *)calloc(5,sizeof(int)); // allocates 5 ints
    q = (int *)malloc(5 * sizeof(int)); // allocates 5 ints gasp

    So, what's the idea behind having the two different memory allocation functions?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    >What exactly is the difference
    Supposedly calloc is there to improve the syntax of malloc so that it's easier to understand. They both finish with the same result but each gets there in a different way, malloc takes the complete size for a block of memory to allocate as an argument and calloc takes the number of elements and the size of each element as arguments.

    calloc will do the calculation for the size of the entire block to allocate insude the function while malloc doesn't need to. This probably saves an instruction or two, but is really not that important. Most people will use malloc because it is the most common.

    Another difference is in how the allocated memory is initialized. malloc does nothing to initialize the memory it allocates but calloc will attempt to initialize the memory to all bits zero if possible.

    My best code is written with the delete key.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc, calloc from the FAQ
    By salvadoravi in forum C Programming
    Replies: 10
    Last Post: 01-21-2008, 03:29 AM
  2. Malloc & Calloc difference in terms of memory allocated
    By swapnaoe in forum C Programming
    Replies: 2
    Last Post: 04-19-2007, 12:57 AM
  3. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  4. difference between calloc and malloc
    By saravanan_ts in forum C Programming
    Replies: 4
    Last Post: 07-28-2003, 06:13 AM