Re: Are the following 2 code statements equivalent
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Wed, 14 Feb 2007 16:33:47 -0800
"ababeel" <farooq.omar@xxxxxxxxx> writes:
Pretty basic question....
is doing
char **p = calloc(mysize, sizeof(char *));
same as doing
char **p = malloc(mysize*sizeof(char *));
memset(p,0,mysize*sizeof(char *));
Pretty much, but there are some subtle differences.
Unsigned multiplication does not overflow; if the result doesn't fit
in the type (size_t in this case), it's reduced modulo 2**N, where the
largest value of the type is 2**N-1, yielding a value smaller than the
straightforward mathematical result. In the calloc() case, the
multiplication is implicit; if the result would wrap around, calloc()
is not allowed to allocate some smaller amount. It must either
allocate the full amount requested (there's been some debate on a
sub-point of this, but don't worry about it) or fail and return a null
pointer. (Some calloc() implementations get this wrong, BTW.) Also,
if calloc() fails to allocate the requested memory, it won't attempt
to zero it.
In the second sequence, the multiplication is done in user code. If
it wraps around, the wrapped value is passed to malloc(), which has no
way of knowing that anything went wrong. This can result in a smaller
allocation than what you tried to ask for.
You call memset() without checking the result of the malloc() call.
If malloc() fails, it returns a null pointer, and the call to memset()
invokes undefined behavior.
You don't show us the definition of "mysize". It's possible I could
come up with even more nitpicking based on that, but I won't bother.
There shouldn't be a problem if it's of type size_t.
In both code fragments you set the allocated memory (which you're
presumably going to treat as an array of pointers) to all-bits-zero,
which is *not* necessarily the representation of a null pointer.
You're better off using malloc() *without* the memset(), and just
being careful not to refer to element of the allocated array before
they've been initialized.
And, of course, the preferred way to call malloc() is:
char **p = malloc(mysize * sizeof *p);
for reasons that have been explained here many many times.
Apart from that, yes, they're pretty much equivalent.
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.
- References:
- Are the following 2 code statements equivalent
- From: ababeel
- Are the following 2 code statements equivalent
- Prev by Date: Re: Are the following 2 code statements equivalent
- Next by Date: Re: int urldecode(char *src, char *last, char *dest)
- Previous by thread: Re: Are the following 2 code statements equivalent
- Next by thread: Program repeats itself, pointer trouble I suspect.
- Index(es):
Relevant Pages
|