calloc() vs. malloc()

This is a discussion on calloc() vs. malloc() within the C Programming forums, part of the General Programming Boards category; Hi, Suppose I wished to initialize a dynamically allocated array of integers to zero. Would I do better to use ...

  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,675
    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,675
    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
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,658
    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
    Registered User
    Join Date
    Oct 2011
    Posts
    834
    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,675
    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,675
    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
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,658
    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
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,658
    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, 03:54 PM
  5. Calloc vs. Malloc
    By SavesTheDay in forum C Programming
    Replies: 3
    Last Post: 02-18-2002, 02:56 PM

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