Re: CurrentElement->next = CurrentElement->next->next (UNDEFINED?)

From: Andrey Tarasevich (andreytarasevich_at_hotmail.com)
Date: 03/09/05


Date: Tue, 08 Mar 2005 16:45:07 -0800

Deniz Bahar wrote:
> ...
> I'm working with a single linked list and want to delete elements by
> searching through the list (starting form the HEAD) then finding the
> element, then doing the following:
>
> NewElement = CurrentElement->next;
> CurrentElement->next = NewElement->next->next;
> free(NewElement);
>
> Does the double ->next invoke undefined behaviour (sequence points
> etc)?
> ...

No. Firstly, you are not accessing the same object twice.
'CurrentElement->next' as an lvalue is neither 'NewElement' nor
'NewElement->next' nor 'NewElement->next->next'. There's no problem with
sequence points here.

However, the code itself doesn't do what it is supposed to do. Doing

  NewElement = CurrentElement->next;
  CurrentElement->next = NewElement->next->next;

will exclude _two_ consecutive elements from the list (both 'NewElement'
and 'NewElement->next'), not one. Apparently, this is not what you
wanted to do. You probably intended to do either

  NewElement = CurrentElement->next;
  CurrentElement->next = NewElement->next;

or

  NewElement = CurrentElement->next;
  CurrentElement->next = CurrentElement->next->next;

That would exclude only one element from the list.

Now in that last version the value of 'CurrentElement->next' is accessed
twice (once to read it and once to modify it), which might rise the
question about sequence points etc. However, it this case everything is
fine too. The old value of 'CurrentElement->next' is read for the sole
purpose of determining its new value.

-- 
Best regards,
Andrey Tarasevich


Relevant Pages

  • head gasket replacement 92 saturn SL2
    ... Disassembled, confirmed gasket failure. ... Head is fined, cleaned up ... bought new bolts and gasket. ... install the bolts and tighten them, in sequence, to ...
    (rec.autos.tech)
  • Re: Increment operator
    ... the second time the function is called has to happen after the ... stored value of any object twice between the previous and next ... sequence point; the two 'i's refer to two different objects. ... it's intended to break a hypothetical conforming implementation ...
    (comp.lang.c)
  • Re: Retorqing Head
    ... I had to change the block but when it came to the head I ... >>> you have installed the updated Torx Head bolts that warming the engine ... >>> is not included in the sequence. ... >>> It states for the Torx Bolts ...
    (alt.autos.bmw)
  • Re: Simple search across lines?
    ... > [on ignoring newlines when searching] ... > If you ignred newlines as a character, the "you\ndid" sequence above ...
    (comp.editors)
  • Re: Interesting puzzle
    ... |any infinite binary sequence, some head of that sequence is a member ... |of the collection (by a head of a sequence, I mean the string formed ... "if a finitely branching tree ...
    (sci.math)