Thread: What is Calloc in C?

  1. #1
    Registered User
    Join Date
    Apr 2020
    Posts
    14

    What is Calloc in C?

    Hi guys,

    I tried to understand calloc function in c language I have gone through the many pages but I do not understand fundamental What is Calloc in C?

    Code:
    #include<stdio.h>#include<stdlib.h>
    
    
    int main() {
    
    
        int* a = (int*) calloc(5, sizeof(int));
    
    
        return 0;
    }
    I understand malloc if there was malloc that means allocate memory for five elements that is integer

    What's is use of Calloc in memory allocation ?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,944
    That article gives you your answer: to malloc and "initialize it to zero"
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Apr 2020
    Posts
    14
    Quote Originally Posted by laserlight View Post
    That article gives you your answer: to malloc and "initialize it to zero"
    exactly I do not understand what it means "initialize it to zero"

    If we want to store value of five integer we need 20 bytes so malloc function will allocate 20 bytes to store five integer value because it integer takes one byte to store integer value

    How calloc is different then malloc

  4. #4
    Registered User
    Join Date
    Aug 2019
    Location
    inside a singularity
    Posts
    307
    calloc and malloc are the same thing. calloc just sets the integer to value 0. So, if you allocate using malloc, and peek at the value of the variable, it can be anything from INT_MIN to INT_MAX (for int, obviously). If you allocate using calloc, value will be set to 0.

    > it integer takes one byte to store integer value

    No, integer will take 4 bytes to store the value if it takes 20 bytes to store five integer values.
    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning." - Rick Cook, The Wizardry Compiled

  5. #5
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    740
    Quote Originally Posted by muke786 View Post
    exactly I do not understand what it means "initialize it to zero"

    If we want to store value of five integer we need 20 bytes so malloc function will allocate 20 bytes to store five integer value because it integer takes one byte to store integer value

    How calloc is different then malloc
    malloc() and calloc() will both allocate memory on the heap for use by the program.

    malloc() will allocate the memory, but the all the memory allocated will contain unknown values in each byte of the allocated space.

    calloc() will allocate the memory, but will set the value of each of the bytes allocated to binary 0, or all bits in the byte will be set to 0.

    BTW, you should not, and need not cast the return from malloc() and calloc()!
    Code:
    int* a = (int*) calloc(5, sizeof(int));
    
    // Should be:
    
    int* a = calloc(5, sizeof(int));
    See the manpage for both functions online, or "man calloc" on the Linux command line.

  6. #6
    Registered User
    Join Date
    Apr 2020
    Posts
    14
    Quote Originally Posted by Zeus_ View Post
    calloc and malloc are the same thing. calloc just sets the integer to value 0. So, if you allocate using malloc, and peek at the value of the variable, it can be anything from INT_MIN to INT_MAX (for int, obviously). If you allocate using calloc, value will be set to 0.

    Does this mean that when we allocate memory through malloc, the garbage value will stored at that memory location. When we allocate memory through calloc, every variable will initialized to 0.

  7. #7
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,883
    Quote Originally Posted by muke786 View Post
    Does this mean that when we allocate memory through malloc, the garbage value will stored at that memory location. When we allocate memory through calloc, every variable will initialized to 0.
    Learn by doing

    Code:
    int main(void)
    {
        int i, setSize = 10;
        char *apple;
    
        apple = malloc(setSize * sizeof(*apple));
    
        if (apple != NULL)
        {
            printf("\nmalloc: ");
            for (i=0; i<setSize; i++)
            {
                printf("0x%x ", apple[i]);
            }
        }
    
        free(apple);
    
    
        apple = calloc(setSize, sizeof(*apple));
    
        if (apple != NULL)
        {
            printf("\ncalloc: ");
            for (i=0; i<setSize; i++)
            {
                printf("0x%x ", apple[i]);
            }
        }
    
        free(apple);
    
        fflush(stdout);
    
        return 0;
    }
    Fact - Beethoven wrote his first symphony in C

  8. #8
    Registered User
    Join Date
    Dec 2017
    Posts
    967
    malloc reuses memory without zeroing it, so it may not be all zeroes. calloc simply zeroes the bytes after allocating them. Basically it's just malloc followed by a memset, although it also has a different signature for some reason.
    Code:
    void* my_calloc(size_t num, size_t size)
    {
        void *p = malloc(num * size);
        return p ? memset(p, 0, num * size) : NULL;
    }
    As long as all-bytes-zero means zero for your variable type (or NULL for your pointer type) then you can say that they are set to zero (or NULL).
    If you want the truth to stand clear before you, never be for or against. - Sent-ts'an

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,178
    > As long as all-bytes-zero means zero for your variable type (or NULL for your pointer type)
    Question 7.31

    Weird machines are few and far between.
    Question 5.17

    It might be hard to see anything from Click_here's example.
    Memory is often (always, because you know - privacy and security) cleared to zeros by the OS, so the first time you call malloc, it often reads as zeros anyway.

    If it isn't cleared by the OS, your library malloc might still clear it (as mine does).
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(void)
    {
        int i, setSize = 10;
        char *apple;
    
        apple = malloc(setSize * sizeof(*apple));
        printf("Ptr=%p",(void*)apple);
        if (apple != NULL)
        {
            printf("\nmalloc: ");
            for (i=0; i<setSize; i++)
            {
                printf("0x%x ", apple[i]);
            }
        }
        strcpy(apple,"Secret");
        free(apple);
    
        // That was fun, let's do it again
        apple = malloc(setSize * sizeof(*apple));
        printf("\nPtr=%p",(void*)apple);
        if (apple != NULL)
        {
            printf("\nmalloc: ");
            for (i=0; i<setSize; i++)
            {
                printf("0x%x ", apple[i]);
            }
        }
        strcpy(apple,"Secret");
        free(apple);
    
        apple = calloc(setSize, sizeof(*apple));
        printf("\nPtr=%p",(void*)apple);
        if (apple != NULL)
        {
            printf("\ncalloc: ");
            for (i=0; i<setSize; i++)
            {
                printf("0x%x ", apple[i]);
            }
        }
    
        free(apple);
    
        fflush(stdout);
    
        return 0;
    }
    
    $ ./a.out 
    Ptr=0x1dd3010
    malloc: 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 
    Ptr=0x1dd3010
    malloc: 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 
    Ptr=0x1dd3010
    calloc: 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0
    Each alloc comes back with the same address each time, but there is never any trace of the previous contents.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,883
    Memory is often (always, because you know - privacy and security) cleared to zeros by the OS, so the first time you call malloc, it often reads as zeros anyway.
    Good point - I didn't think of that

    My OS does not clear the memory before allocating it, so here is the output from when I ran it (in case you are in the same boat as Salem)
    Code:
    malloc: 0x41 0x2F 0x84 0x0 0x52 0x17 0x44 0x0 0x63 0x4f
    calloc: 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0
    Process returned 0 (0x0)   execution time : 0.070 s
    Press any key to continue.
    Fact - Beethoven wrote his first symphony in C

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,178
    > malloc: 0x41 0x2F 0x84 0x0 0x52 0x17 0x44 0x0 0x63 0x4f
    Mmm, any juicy secrets in there if you say dump a couple of megabytes to a file and examine it with a hex editor?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  12. #12
    Registered User
    Join Date
    Dec 2017
    Posts
    967
    Quote Originally Posted by Click_here View Post
    My OS does not clear the memory before allocating it
    If you are using Windows, Linux or Mac then the OS zeroes any new memory pages allocated to a process since otherwise you could literally see data from a different program, possibly even a different user!
    However, the allocation routines built on top of the basic OS page allocator will generally not zero the memory with malloc.
    In fact, I doubt that Salem's system zeroes the memory for any large allocation, say 10,000 bytes.
    If you want the truth to stand clear before you, never be for or against. - Sent-ts'an

  13. #13
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,883
    Mmm, any juicy secrets in there if you say dump a couple of megabytes to a file and examine it with a hex editor?
    If it's my meme collection you are after, you can go away :P
    Fact - Beethoven wrote his first symphony in C

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. calloc
    By dunsta in forum C Programming
    Replies: 5
    Last Post: 05-05-2010, 08:31 AM
  2. re-calloc???
    By audinue in forum C Programming
    Replies: 6
    Last Post: 07-20-2008, 05:06 PM
  3. calloc
    By goran00 in forum C Programming
    Replies: 27
    Last Post: 04-07-2008, 12:50 PM
  4. Using calloc
    By giancu in forum C Programming
    Replies: 10
    Last Post: 11-07-2007, 01:32 PM
  5. Why use calloc()?
    By dwks in forum C Programming
    Replies: 8
    Last Post: 07-20-2005, 08:22 AM

Tags for this Thread