Thread: calloc() vs. malloc()

  1. #1
    Registered User
    Join Date
    Apr 2013
    Posts
    122

    calloc() vs. malloc()

    Hi,
    Suppose I wished to initialize a dynamically allocated array of integers to zero. Would I do better to use calloc() or malloc + iterate over all entries setting each to zero? Which one is regarded as a better approach?

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    This one seems reasonable to me:

    If you need the dynamically allocated memory to be zero-initialized then use calloc.

    If you don't need the dynamically allocated memory to be zero-initialized, then use malloc.

    You don't always need zero-initialized memory; if you don't need the memory zero-initialized, don't pay the cost of initializing it. For example, if you allocate memory and then immediately copy data to fill the allocated memory, there's no reason whatsoever to perform zero-initialization.

    calloc and malloc are functions that do different things: use whichever one is most appropriate for the task you need to accomplish.

    ~I copy pasted this from a link found in google.
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  3. #3
    Registered User
    Join Date
    Apr 2013
    Posts
    122
    Great, thank you.

  4. #4
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    You are welcome. Very "good" question by the way the one you made
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  5. #5
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Calloc() should work if you want to zero initialize an array of ints. The real so-called problem with calloc() is that it will initialize all bits to zero, which is not necessarily the zero value for every data type.

  6. #6
    Ticked and off
    Join Date
    Oct 2011
    Location
    La-la land
    Posts
    1,728
    calloc(), because on some architectures and cases it can be optimized (to basically avoid the clearing completely).

    When a process asks more memory from a kernel via an anonymous memory map, most systems guarantee it's already cleared to zero. A C library can use that to only clear -- using a fast, optimized memset() variant for just this purpose -- parts it knows might be dirtied, and avoid "clearing" those already-cleared pages.

    The larger the allocated area, the more beneficial it is (on some architectures, not necessarily on all) to use calloc() instead of malloc()+memset().

    (If you are working in the Linux world, and you or your library locks memory pages, there was a bug in the GNU C library, where it forgot to check if anonymously mapped pages were actually cleared or not. Sometimes the data was not really cleared to zeroes! This only affects the cases where the application/library locked at least some pages in memory using mlock() or mlockall(), and it's fixed in glibc 2.8.)

    If you wish to "clear" the array to a predefined entry (not just all bits zero), it is best to use malloc(), populate the initial entry of the array, and then use e.g.
    Code:
    void memfill(void *const array, const size_t size, const size_t count)
    {
        const size_t full = size * count;
        const size_t half = size * count / 2;
        size_t  have = size;
    
        while (have <= half) {
            memmove((char *)array + have, array, have);
            have *= 2;
        }
    
        if (have < full)
            memmove((char *)array + have, array, full - have);
    }
    which copies the initial size bytes (the first entry) to all count entries in the array, no matter what the entries really contain. It works by repeatedly copying the filled part of the array to the rest of the array. It does log2 count passes, and due to cache effects is not the fastest one there is, but it is fast and robust on all architectures.

    Funnily enough, on most architectures a function that works like memcpy() but copies overlapping regions in exactly the opposite order memmove() does -- so almost a duplicate of memmove(), just pass direction reversed! --, is the fastest one. But, neither the C standard nor any C library I know of provide that function. If they did, certain benchmarks which show that "Fortran code is faster than C code", would be finally fixed with standard C. Most Fortran compilers, you see, use something pretty much exactly that to fill arrays (slices) with a constant value, and it is much faster than copying individual values.

  7. #7
    Registered User
    Join Date
    Apr 2013
    Posts
    122
    I have an array of ints where each entry is expected to be a counter, i.e. must be initialized to zero this way or the other before the actual count begins. That would justify calloc(), wouldn't it? (wish to make sure)

  8. #8
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Can you give an example to demonstrate what are saying whitef?
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  9. #9
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Quote Originally Posted by peripatein View Post
    I have an array of ints where each entry is expected to be a counter, i.e. must be initialized to zero this way or the other before the actual count begins. That would justify calloc(), wouldn't it? (wish to make sure)
    Since they are counters, calloc would be fine.
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  10. #10
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by std10093 View Post
    Can you give an example to demonstrate what are saying whitef?
    I wouldn't initialize an array of structs with calloc.

  11. #11
    Registered User
    Join Date
    Apr 2013
    Posts
    122
    It's not an array of structs. It's a dynamically allocated array of integers.

  12. #12
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by peripatein View Post
    It's not an array of structs. It's a dynamically allocated array of integers.
    I know that, but I wasn't answering your question anymore.

  13. #13
    Registered User
    Join Date
    Apr 2013
    Posts
    122
    No problem :-)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Using malloc instead of calloc
    By sangamesh in forum C Programming
    Replies: 6
    Last Post: 04-24-2012, 04:01 AM
  2. malloc and calloc
    By rrc55 in forum C Programming
    Replies: 15
    Last Post: 09-02-2009, 07:35 PM
  3. Malloc vs. Calloc
    By FCF in forum C Programming
    Replies: 13
    Last Post: 06-30-2002, 06:41 PM
  4. calloc vs malloc
    By Jubba in forum C Programming
    Replies: 2
    Last Post: 02-21-2002, 04:54 PM
  5. Calloc vs. Malloc
    By SavesTheDay in forum C Programming
    Replies: 3
    Last Post: 02-18-2002, 03:56 PM