Re: difference between calloc() and malloc()
On Feb 14, 8:44 pm, Jeff Schwab <j...@schwabcenter.com> wrote:
Victor Bazarov wrote:
Jeff Schwab wrote:
Pete Becker wrote:
On 2008-02-14 13:09:06 -0500, Jeff Schwab <j...@schwabcenter.com>
said:
James Kanze wrote:
The way raw memory is usually allocated in C++ is by calling the
operator new() function. malloc() can also be used. calloc()
should probably be avoided, both in C and in C++, because it
masks a number of serious errors.
What are the problems with calloc? Googling "calloc errors" and
"problems with calloc" did not turn up anything obvious.
It sets all the bytes in the allocated memory to 0. All too often,
that will mean that uninitialized data members look like they have
legitimate values.
Huh? That's not only the documented behavior, it's the primary reason
to use calloc. I specifically have used it in the past to avoid
having to zero-out memory manually, which I do to make sure that the
program's behavior is at least deterministic. This is considered a
bad thing?
I believe what Pete refers to is, if you forget to initialise
a member to something meaningful, then the use of 'calloc' when
allocating your class object dynamically would hide the fact
that you didn't initialise that member, and instead create
a false sense of security. When an object of the same type is
instantiated in automatic storage (local object, argument), the
uninitialised member will play some role, possibly detrimental,
and the bug would be difficult to track.
Thank you, that makes some sense. I guess I'm at odds with the
prevailing wisdom here, though. I still prefer this:
auto primitive_t a[size] = { 0 };
To that:
auto primitive_t b[size];
Yes, but that's not what calloc does. Calloc sets all of the
bits in the memory to 0, regardless of the type. Consider
something like:
void* a[ size ] = {0} ;
This initializes the array with null pointers. Calloc only
initializes the allocated memory with null pointers IF a null
pointer is represented by all bits 0, which while frequent,
isn't necessarily the case. So if you test on a machine where
null pointers are all bits 0, you have the impression that the
code works, even though you haven't correctly initialized the
memory.
If a local vector is used rather than an array (or a calloc'd block of
memory), I'm not even sure how to specify that the memory should be left
uninitialized...
auto std::vector<primitive_t> v(size, ?);
You can't. std::vector does not allow uninitialized objects.
It can't---an uninitialized object is not copiable (unless it is
of character type).
AFAIK, static objects are guaranteed to be zero'd by all conformant
implementations, too.
They are guaranteed to be "zero initialized". That doesn't
necessarily mean all bits 0.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34