Re: [PATCH] git-compat-util.h: introduce CALLOC(x)

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Mon, Dec 05, 2022 at 07:29:22PM -0500, Taylor Blau wrote:

> On Tue, Dec 06, 2022 at 08:57:21AM +0900, Junio C Hamano wrote:
> > Taylor Blau <me@xxxxxxxxxxxx> writes:
> >
> > > In git.git, it is sometimes common to write something like:
> > >
> > >     T *ptr;
> > >     CALLOC_ARRAY(ptr, 1);
> > >
> > > ...but that is confusing, since we're not initializing an array.
> >
> > Given that "man calloc" tells us that calloc takes two parameters,
> >
> >     void *calloc(size_t nmemb, size_t size);
> >
> > I personally find CALLOC() that takes only a single parameter and is
> > capable only to allocate a single element array very much confusing.
> 
> Hmm. I have always considered "calloc" a mental shorthand for "zero
> initialize some bytes on the heap". It seemed like you were in favor of
> such a change in:
> 
>     https://lore.kernel.org/git/xmqq8rl8ivlb.fsf@gitster.g/
> 
> ...but it's entirely possible that I misread your message, in which case
> I would not be sad if you dropped this patch on the floor since I don't
> feel that strongly about it.

I think the weird thing about calloc is that it does _two_ things
compared to malloc: zero-ing, and doing an implicit nmemb*size
multiplication.

So you can think of "allocate this one element and zero it" as "calloc,
but don't multiply" or as "malloc, but zero". Naming it CALLOC() is
thinking of it as the former. If we think of it as the latter it could
perhaps be MALLOCZ() or something. I don't know if that name is too
subtle or not. We have xmemdupz(), which is basically the same thing;
it's only a zero-terminator, but that is because we are writing non-zero
bytes in the rest of it. Mostly I'd worry that it is easy to glance past
the "Z".

-Peff



[Index of Archives]     [Linux Kernel Development]     [Gcc Help]     [IETF Annouce]     [DCCP]     [Netdev]     [Networking]     [Security]     [V4L]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux Security]     [Linux RAID]     [Linux SCSI]     [Fedora Users]

  Powered by Linux