Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C tutorial question relating to calloc vs malloc

I am following this tutorial (http://theocacao.com/document.page/234). I am confused about this paragraph, mainly the lines relating to calloc:

We can also use a variation of the malloc function, called calloc. The calloc function takes two arguments, a value count and the base value size. It also clears the memory before returning a pointer, which is useful in avoiding unpredictable behavior and crashes in certain cases:

That last line confuses me. What does it mean to clear the memory?

like image 774
chrisgoyal Avatar asked Feb 06 '10 19:02

chrisgoyal


People also ask

Why is realloc () needed when calloc () and malloc () is already available?

C realloc() method “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.

What is the difference between malloc () and calloc () Explain with example program the working of malloc () calloc () and free ()?

Difference Between calloc() and malloc() Malloc() function will create a single block of memory of size specified by the user. Calloc() function can assign multiple blocks of memory for a variable. Malloc function contains garbage value. The memory block allocated by a calloc function is always initialized to zero.

What are calloc and malloc in C with example?

calloc() versus malloc() in C It works similar to the malloc() but it allocate the multiple blocks of memory each of same size. Here is the syntax of calloc() in C language, void *calloc(size_t number, size_t size); Here, number − The number of elements of array to be allocated.

Can I use calloc instead of malloc?

Use malloc() if you are going to set everything that you use in the allocated space. Use calloc() if you're going to leave parts of the data uninitialized - and it would be beneficial to have the unset parts zeroed.


1 Answers

The function calloc will ensure all bytes in the memory returned are set to 0. malloc makes no such guarantees. The data it returns can, and will, consist of seemingly random data.

The distinction is very useful for initialization of data members. If 0 is a good default for all values in a struct then calloc can simplify struct creation.

Foo* pFoo = calloc(1, sizeof(Foo));

vs.

Foo* pFoo = malloc(sizeof(Foo));
pFoo->Value1 = 0;
pFoo->Value2 = 0;

Null checking omitted for clarity.

like image 188
JaredPar Avatar answered Sep 30 '22 01:09

JaredPar