I was wondering what calloc() is good for (besides setting everything to zero). As far as I can see,
is the same asCode:calloc(x, y);
(Except for calloc setting the allocated memory to zero.)Code:malloc(x*y);
So what is calloc() good for?
Printable View
I was wondering what calloc() is good for (besides setting everything to zero). As far as I can see,
is the same asCode:calloc(x, y);
(Except for calloc setting the allocated memory to zero.)Code:malloc(x*y);
So what is calloc() good for?
Like you said, for initializing the allocated memory to 0...Code:So what is calloc() good for?
If you wanted to you could live your entire life without using calloc() by just doing:
...instead.Code:void *ptr = malloc(SIZE);
memset(ptr, 0, SIZE);
That's what I thought . . . .
On some systems the calloc call could be optimized better for getting arrays of zeroed bytes. The system can keep a list of zeroed out memory and non-zeroed memory so calloc can look up memory in the zero pool while malloc returns pointers to the other pool and the memset is extra overhead that was already done on an idle moment for the zero pool.
Windows does that for instance. When the system is idle it starts the zero page thread. I don't know about calloc implementations that make use of it thuogh.
http://www.eskimo.com/~scs/C-faq/q7.31.html
Read the health warning.
So it initialises to zero not NULL?
> So it initialises to zero not NULL?
Yes, calloc is nothing more than malloc + memset - the result is a block of memory with all bits set to 0.
But nothing in C insists that NULL (as a pointer) has to be represented by all-bits-zero
http://www.eskimo.com/~scs/C-faq/s5.html
void *p = NULL;
if ( p == NULL )
if ( p == 0 )
These will always be true, whether your machine uses all-bits-zero for a NULL pointer or not.
void *p; memset( &p, 0, sizeof(void*) ); // just what calloc would do
if ( p == NULL )
if ( p == 0 )
These will work on some machines, and not on others.
Do you know of any system where this is true btw? I'm not questioning the portability issue, just curious.Quote:
Originally Posted by Salem