Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent code for calloc

Tags:

c++

c

In the given c code snippet what will be the equivalent code for the line int *count = (int *)calloc(sizeof(int), 256); ?

int *getCharCountArray(char *str)
{
   int *count = (int *)calloc(sizeof(int), 256);
   int i;
   for (i = 0; *(str+i);  i++)
      count[*(str+i)]++;
   return count;
}

Whether it is possible to do this without using calloc? How we can declare this using malloc and new in c++ ?

like image 539
nathan1138 Avatar asked Mar 30 '13 21:03

nathan1138


People also ask

Is it better to use malloc () or calloc ()?

The number of arguments in calloc() is 2. 3. malloc() is faster. calloc() is slower.

What is calloc short for?

Calloc stands for contiguous allocation. Malloc function is used to allocate a single block of memory space while the calloc function in C is used to allocate multiple blocks of memory space. Each block allocated by the calloc in C programming is of the same size.

What does calloc do in C?

“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type.

What is the return type of malloc () or calloc ()?

Explanation: malloc() and calloc() return void *.


2 Answers

calloc is basically equivalent to malloc followed by memset to set all the data to zero bytes:

void *like_calloc(size_t size, size_t num) { 
    void *ret = malloc(size * num);

    if (ret)  
        memset(ret, 0, size * num);
    return ret;
}

C++ provides a syntax for new that lets you do this a little more simply:

int *count = new int[256]();

Note the parens at the end. Also note, however, that you generally do not want to do this in C++ at all -- you'd normally want to write the code something like this:

std::vector<int> getCharCountArray(unsigned char const *str) { 
     std::vector<int> count(std::numeric_limits<unsigned char>::max()+1);

     for (int i=0; str[i]; i++)
         ++count[str[i]];
     return count;
}

This obviously simplifies the code a fair amount, but there's more simplification than may be immediately obvious too. Specifically, this avoids the rest of the code having to track when the returned value is no longer needed, and deleting the memory at that point (but no sooner) as is needed with either the C version or the version using new in C++.

like image 120
Jerry Coffin Avatar answered Oct 12 '22 13:10

Jerry Coffin


This will allocate 256 ints, and value-initialize the array to 0

This does what calloc is doing in your code.

int *count = new int[256]();
//                       ^^ value-initialization
like image 29
Drew Dormann Avatar answered Oct 12 '22 11:10

Drew Dormann