When should I use calloc over malloc

This is from the Beej manual to C "The disadvantage of using calloc () is that it takes time to clear the memory, and in most cases you do not need it clearly, as you will just write over it anyway. But if you you will find malloc () in the block, and then immediately set the memory to zero, you can use calloc () to do this in one call.

so there is a potential scenario when I want to clear the memory to zero.

+6
source share
5 answers

When a function you pass a buffer to a state in your documentation, that buffer should be filled with zeros. You can also always reset the memory for security; in fact, it does not take much time if the buffers are really huge. Memory allocation itself is a potentially expensive part of the operation.

+8
source

In one scenario, you allocate an array of integers (for example, like batteries or counting variables), and you want each element in the array to start with 0.

+5
source

In some case, when you allocate memory for some structure, and some member of this structure can be evaluated in some expression or in a conditional expression without initializing this structure, in this case it will be harmful or give you undefined behavior. So overcome the form, it is better than you.

1> malloc that structure and memset it with 0 before using that structure 

or

 2> calloc that structure 

Note. Some memory management programs with malloc memory also reset from 0

+1
source

There are many times when you may want to reset your memory!

Some examples:

  • Allocating memory to place the structure where you want all members initialized to zero
  • The allocation of memory for an array of characters, which you later intend to write to a number of characters, and then process as a NULL complete string
  • Memory allocation for an array of pointers that you want to initialize with NULL
0
source

If all of the allocated memory is filled with zeros, the behavior of the program is much more reproducible (so the behavior will most likely be the same if you re-run your program). This is why I do not use malloc uninitialized zones.

(for the same reasons, when debugging a program in C or C ++ on Linux, I usually do echo 0 > /proc/sys/kernel/randomize_va_space , so the behavior of mmap more reproducible).

And if your program does not allocate huge blocks (i.e. tens of megabytes), the time spent inside malloc is much longer than the time to zero.

0
source

Source: https://habr.com/ru/post/901359/


All Articles