C - calloc() v. malloc() [duplicate]
Possible Duplicate:
c difference between malloc and calloc
Please explain the significance of this statement,
Another differenc开发者_StackOverflow中文版e 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
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.
calloc
is initializing the memory before you use it, but malloc
does not.
Refer to this link:
The calloc() function shall allocate unused space for an array of nelem elements each of whose size in bytes is elsize. The space shall be initialized to all bits 0.
With malloc
, if you want to guarantee the same effect you'd have to call something like memset to reset the memory, e.g.
char* buffer = (char*)malloc(100);
memset(buffer,0,100);
calloc
saves you that extra step.
The significance of initializing memory is that you are getting a variable to a known state rather than an unknown one. So if you are checking a variable, say an array element, for an expected value, then by having pre-initialized the variable ahead of time, you can be sure that the value you are checking isn't garbage. In other words, you can distinguish between garbage and legitimate values.
For example, if you just leave garbage in the variable and you are checking for some value, say 42, then you have no way of knowing if the value was really set to 42 by your program, or if that's just some garbage leftover because you didn't initialize it.
calloc(...)
is basically malloc
+ memset
(if you want to 0 initialise the memory)
ptr = malloc(sizeof(struct fubar));
memset(ptr, 0, sizeof (struct fubar)); //here we could use some different value instead of 0 whereas calloc always 0 initialises.
When you use malloc
to allocate some memory, it's previous contents are not cleared (ie not initialized). You might get random values that were set when machine booted up or you might see some of the memory that belonged to previously running programs but was left uncleared after allocation and program exit.
calloc
itself is slower than malloc
because you have to spend some time to clear the contents of allocated memory. So if you just need to allocate some memory and then copy some stuff there, you are free to use malloc
.
It just means that if you allocate memory, with calloc(), whatever you allocate is 0. i.e. if you allocated space for an array of integers, they'd all be set to 0, whereas with malloc(), the memory there isn't initialized in any way.
You could use calloc in situations where you are just going to do a memset of 0 to the memory anyway.
精彩评论