Re: linked list (c programming)

From: Roger Willcocks (rkww_at_rops.org)
Date: 02/17/04


Date: Mon, 16 Feb 2004 23:02:54 -0000


"Richard Heathfield" <dontmail@address.co.uk.invalid> wrote in message
news:c0oiu8$l1n$1@hercules.btinternet.com...
> Roger Willcocks wrote:
>
> > "chrismiceli" <chrismiceli@excite.com> wrote in message
> > news:3751a0cb.0402141523.4c74b4ab@posting.google.com...
> >> here is some linked list code, it segfaults after the printf of hello,
> >> any help would be greatly appreciated.
> >>
> > ...
> >
> > You get a segfault because in add_node you've allocated space for the
next
> > entry in the list but you haven't initialized that space.
> >
> >> current->next = (struct name_layout *)malloc(sizeof (struct
> > name_layout));
> >
> >
> > you should add 'memset(current->next, 0, sizeof(struct name_layout))' or
> > similar, after you allocate the memory, to get it into a known state
> > rather than assuming malloc will do this for you.
>
> memsetting it to 0 will set it to all-bits-zero, which is not /guaranteed/
> to set a pointer to NULL (which is what is required here). On the OP's
> platform, it will probably work, but that's not the same thing as being
> right.

Point taken, but to be pedantic I did actually say 'get [the memory] into a
known state' using memset or similar - not 'initialize it to useful starting
values for the algorithm.' Leaving old values laying about in newly
allocated memory invites a whole slew of interesting, platform-dependent and
hard-to-find bugs which are best avoided.

Think 'principle of least surprise.'

>From a debugging point of view it would be best if the allocator could
initialize memory to 'unitialized' - if you see what I mean: 'first program
access must be a write.'

> He should set the fields separately. (See my parallel reply.)

Yep.

--
Roger