[tpop3d-discuss]alternative implementation of alloc_struct(S, p)

Chris Lightfoot chris at ex-parrot.com
Mon, 13 Feb 2006 20:25:32 +0000


On Mon, Feb 13, 2006 at 09:06:02PM +0100, Maurice van der Pot wrote:
> Hey guys,
> 
> I've been running into a problem with the gcc stack protector code that
> surfaced because of the use of a locally declared variable in alloc_struct
> (util.h:51).
> 
> It turns out that if alloc_struct is rewritten to look like this:
> 
>   #define alloc_struct(S, p)  do { p = xmalloc(sizeof *p); memset(p, 0, sizeof(*p)); } while (0)
> 
> then the problem disappears.
> 
> The bug in the stack protector will be taken care of, but since the alternative
> code is also faster and uses less stack space than the original version of alloc_struct, 
> you may want to consider it for inclusion in tpop3d.
> 
> For details, please read the following bug report and comment #10 and
> #11 in particular:
> 
>   https://bugs.gentoo.org/show_bug.cgi?id=115285
> 
> Best regards,
> Maurice.
> 
> P.S.: You can also drop the S parameter that way.

Your implementation of alloc_struct is not valid. It
assumes that all-bits-zero is a valid representation of
any element of a struct on any architecture, and that that
is the same representation as would be yielded by the =
{0} declaration. There is no such guarantee in the C or
POSIX standards, and while using memset(..., 0, ...) may
work on your architecture it is not portable and therefore
best avoided unless there is some compelling reason to use
it.

As the bug report states this is a GCC problem which can
be fixed by removing the offending options. Note however
that the statement that,

    declaring stuff in local blocks is an extension to
    standard C

is mistaken; you have been able to make such declarations
since C89 at least (I don't have my K&R to hand, but I
think it dates to the very oldest C compilers). It is
declarations in the course of a block which are new in
C99.

-- 
``Tony Blair has made `morale boosting' visits
  to the wives of servicemen serving in the Gulf.'' (BBC News)