[BusyBox] should xmalloc clear memmory ?
Mark Whitley
markw at lineo.com
Mon Feb 12 21:05:52 UTC 2001
On Mon, Feb 12, 2001 at 11:50:46AM +1100, Glenn McGrath wrote:
> Matt Kraai wrote:
> >
> > On Sun, Feb 11, 2001 at 10:48:12AM +1100, Glenn McGrath wrote:
> > > Using grep memset -r *|wc -l
> > >
> > > there are 75 places where we use memset, 5 of them dont set it to 0,
> > > probably a lot of the remaining 70 are happening imediately after
> > > xmalloc.
> > >
> > > So, if we cleared memory inside xmalloc we could remove upto 70
> > > statments.
> > >
> > > Would this be a bad idea for any reason ?
> >
> > xcalloc.
> >
>
> Oh yea, forgot about calloc :)
>
> b.t.w does anyone know why calloc has a different calling structure than
> malloc ?
>
> void *calloc(size_t nmemb, size_t size);
> void *malloc(size_t size);
>
> for calloc why wouldnt they just do
>
> void *calloc(size_t size);
>
> It could always be called like calloc(nemb*size), or am i missing the
> point ?
Historically, malloc is used for allocating memory for a single, scalar
variable. OTOH, calloc has been used historically for making new arrays, hence
the nmemb parameter for specifying the number of elements in the array.
Example:
int *foo = (int *)malloc(sizeof(int)); /* makes a new integer */
int *bar = (int *)calloc(5, sizeof(int)); /* makes an array of 5 integers */
You can use these functions in (ahem) "creative" ways though. Some of the more
popular abuses are:
- Swap the arguments passed to calloc (i.e. calloc(sizeof(int), 5) from the
example above.
- Use malloc instead of calloc and reduce the two parameters to one by doing
malloc(sizeof(int) * 5) (which you've already observed). Unfortunately,
this is all-too-often followed by a memset(&foo, 0, sizeof(foo)) (which
you've also observed). These kinds of cases should really use calloc
instead.
- Use calloc to create a scalar var (instead of an array) by passing it 1 for
nmemb. This can be combined with with abuse #1 like so:
calloc(sizeof(struct foo), 1).
The uClibc implementation of [cm]alloc looks like this:
void *
calloc(size_t nelem, size_t size)
{
void *result;
result = malloc(size * nelem);
if (result)
memset(result, 0, nelem * size);
return result;
}
which just goes to show...
FYI, HTH.
Mark Whitley
markw at lineo.com
More information about the busybox
mailing list