Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - calloc() v. malloc() [duplicate]

Tags:

c

malloc

calloc

Possible Duplicate:
c difference between malloc and calloc

Please explain the significance of this statement,

Another difference between the malloc() and calloc() functions is that the memory allocated by malloc( ) function contains garbage values, while memory allocated by calloc( ) function contains all zeros.

Source ('C' Programming, Salim Y. Amdani)

Thanks

like image 359
Kevin Meredith Avatar asked Aug 10 '10 12:08

Kevin Meredith


People also ask

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

Malloc() VS Calloc(): Explore the Difference between malloc() and calloc() malloc() and calloc() functions are used for dynamic memory allocation in the C programming language. The main difference between the malloc() and calloc() is that calloc() always requires two arguments and malloc() requires only one.

Why is calloc preferred over malloc?

If you need the dynamically allocated memory to be zero-initialized then use calloc . If you don't need the dynamically allocated memory to be zero-initialized, then use malloc . You don't always need zero-initialized memory; if you don't need the memory zero-initialized, don't pay the cost of initializing it.

What happens if you malloc something twice?

When you call malloc a second time, it has no way of knowing you are doing anything with newPtr . It merely allocates new space and returns a pointer to it. Then that new pointer is assigned to newPtr , which erases the old value that was in newPtr .

Can malloc () and memset () can be used to get the same effect as calloc ()?

calloc() allocates the memory and also initializes the allocates memory to zero, while memory allocated using malloc() has random data. malloc() and memset() can be used to get the same effect as calloc(). calloc() takes two arguments, but malloc takes only 1 argument.


1 Answers

From http://wiki.answers.com/Q/Is_it_better_to_use_malloc_or_calloc_to_allocate_memory

malloc() is faster, since calloc() initializes the allocated memory to contain all zeros. Since you typically would want to use and initialize the memory yourself, this additional benefit of calloc() may not be necessary.

like image 175
Edward Leno Avatar answered Sep 21 '22 14:09

Edward Leno