Thursday, 29 March 2018

c - Difference between malloc and calloc?



What is the difference between doing:




ptr = (char **) malloc (MAXELEMS * sizeof(char *));


or:



ptr = (char **) calloc (MAXELEMS, sizeof(char*));


When is it a good idea to use calloc over malloc or vice versa?


Answer




calloc() zero-initializes the buffer, while malloc() leaves the memory uninitialized.



EDIT:



Zeroing out the memory may take a little time, so you probably want to use malloc() if that performance is an issue. If initializing the memory is more important, use calloc(). For example, calloc() might save you a call to memset().


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...