The calloc API

The calloc(3) API is almost identical to malloc(3), differing in two main respects:

  • It initializes the memory chunk it allocates to the zero value (that is, ASCII 0 or NULL, not the number 0)
  • It accepts two parameters, not one

The calloc(3) function signature is as follows:

 void *calloc(size_t nmemb, size_t size);

The first parameter, nmemb, is n members; the second parameter, size, is the size of each member. In effect, calloc(3) allocates a memory chunk of (nmemb*size) bytes. So, if you want to allocate memory for an array of, say, 1,000 integers, you can do so like this:

    int *ptr;
ptr = calloc(1000, sizeof(int));

Assuming the size of an integer is 4 bytes, we would have allocated a total of (1000*4) = 4000 bytes.

Whenever one requires memory for an array of items (a frequent use case in applications is an array of structures), calloc is a convenient way to both allocate and simultaneously initialize the memory.

Demand paging (covered later in this chapter), is another reason programmers use calloc rather than malloc(3) (in practice, this is mostly useful for realtime applications). Read up on this in the up coming section.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset