Re: p = kmalloc(sizeof(*p), )

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

 



Alan Cox <[email protected]> wrote:
> On Maw, 2005-09-20 at 10:11 -0700, Andrew Morton wrote:
> > Russell King <[email protected]> wrote:
> > >  Since some of the other major contributors to the kernel appear to
> > >  also disagree with the statement, I think that the entry in
> > >  CodingStyle must be removed.

> > Nobody has put forward a decent reason for doing so.  

> I've seen five decent reasons so far. Which of the reasons on the thread
> do you disagree with and why ?

Not sure that I'm following the logic here, so...

For one, I leaned towards "p = malloc(sizeof(*p))" before, but the reasons
given for "p = malloc(sizeof struct foo))" (or even "p = (struct foo *)
malloc(sizeof(struct foo))", wrapped in a macro) did convince me.

The gains for a reader/maintainer/code auditor I see:

- It is easier to find it later
- Initialization of *p should be nearby, finding it by type name is useful
  for checking/updating
- It forces you to think a bit before typing it in, this should make making
  mistakes somewhat harder

The loss for a code writer are:

- (Marginally) more typing
- Have to know the type of *p [but if you don't, better don't touch it...]

If the writer has got the type wrong, she will initialize wrongly (and the
compile will blow up), so I don't see any advantage. The only other case
would be something like:

   p = malloc(sizeof(...));
   memset(p, v, sizeof(...));

As v is more often than not 0, this should really be:

   p = calloc(1, sizeof(...));

and perhaps in this case (with /no/ further initialization) it could be
called a tie. For uniformity's sake I'd prefer "sizeof(struct foo)"
everywhere.

In any case, give me help in finding bugs and updating code over (minor)
initial coding convenience everyday.

In any case, as the parallel flamewars conclusively demonstrate, writing it
down in CodingStyle won't make everybody agree on using it anyway, so I'd
vote for including the "sizeof(struct foo)" version there as recommended
practice.
-- 
Dr. Horst H. von Brand                   User #22616 counter.li.org
Departamento de Informatica                     Fono: +56 32 654431
Universidad Tecnica Federico Santa Maria              +56 32 654239
Casilla 110-V, Valparaiso, Chile                Fax:  +56 32 797513
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to [email protected]
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Please read the FAQ at  http://www.tux.org/lkml/

[Index of Archives]     [Kernel Newbies]     [Netfilter]     [Bugtraq]     [Photo]     [Gimp]     [Yosemite News]     [MIPS Linux]     [ARM Linux]     [Linux Security]     [Linux RAID]     [Video 4 Linux]     [Linux for the blind]
  Powered by Linux