difference between calloc and malloc

This is a discussion on difference between calloc and malloc within the C Programming forums, part of the General Programming Boards category; Hi friends, In an interview a question was asked in C to me. The question is: Why we often use ...

  1. #1
    Registered User
    Join Date
    Jul 2003
    Posts
    102

    difference between calloc and malloc

    Hi friends,
    In an interview a question was asked in C to me. The question is:
    Why we often use malloc instead of calloc though calloc provides or intializes the elements to 0 when allocated. I was baffled by this. I have not even thinked about this. I wonder why most of programmers use only malloc. Is there any mem related problems in Calloc or what's the solutions to this. Please let me know about it.
    Saravanan.T.S.
    Beginner.

  2. #2
    Registered User
    Join Date
    Apr 2002
    Posts
    1,571
    Well sometime it is used when you need to set the memory to zero ( obviously ). Often times when you allocate memory you immediately initialize it so it would be wasteful to use calloc in that situation. There is a time and place for each call.
    "...the results are undefined, and we all know what "undefined" means: it means it works during development, it works during testing, and it blows up in your most important customers' faces." --Scott Meyers

  3. #3
    zsaniK Kinasz's Avatar
    Join Date
    Jan 2003
    Posts
    222
    calloc takes more cpu cycles
    "Assumptions are the mother of all **** ups!"

  4. #4
    Registered User
    Join Date
    Jul 2003
    Posts
    18
    I would rather prefer using calloc instead of malloc.I have seen a number of instances when programmers use a combination of malloc and memset calls to allocate and initiliaze memory.I think of instead of using two different calls one could use calloc.

  5. #5
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    I was going to write an answer, but then I remembered there's one in the FAQ already.

    The important thing to remember is relating to NULL pointers (detailed in the FAQ too)
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Difference BW malloc() and calloc() and realloc()
    By svelmca in forum C Programming
    Replies: 2
    Last Post: 03-31-2009, 06:59 AM
  2. malloc, calloc from the FAQ
    By salvadoravi in forum C Programming
    Replies: 10
    Last Post: 01-21-2008, 03:29 AM
  3. Malloc & Calloc difference in terms of memory allocated
    By swapnaoe in forum C Programming
    Replies: 2
    Last Post: 04-19-2007, 01:57 AM
  4. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 06:37 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21