home bbs files messages ]

Just a sample of the Echomail archive

COMPLANC:

<< oldest | < older | list | newer > | newest >> ]

 Message 243,011 of 243,114 
 Keith Thompson to James Russell Kuyper Jr. 
 Re: UB or not UB? was: On Undefined Beha 
 13 Jan 26 22:02:46 
 
From: Keith.S.Thompson+u@gmail.com

"James Russell Kuyper Jr."  writes:
> On 2026-01-13 16:54, Tristan Wibberley wrote:
[...]
>> IIRC indexing a table follows the rules of pointers and doing so
>> outside of a table's bounds is generally U/B except for very peculiar
>> specific cases. You can do it in a struct across members /sometimes/
>> because a struct is a single object. ...
>
> No, there is no such exception in the standard. It is still undefined
> behavior. One of the most annoying ways undefined behavior can
> manifest is that you get exactly the same behavior that you
> incorrectly thought you were guaranteed to get. That's a problem,
> because it can leave you unaware of your error.
[...]

Perhaps the exception Tristan was referring to (though it doesn't apply
to indexing) is this, in N3220 6.5.10p7:

    Two pointers compare equal if and only if both are null pointers,
    both are pointers to the same object (including a pointer to an
    object and a subobject at its beginning) or function, both are
    pointers to one past the last element of the same array object,
    or one is a pointer to one past the end of one array object and
    the other is a pointer to the start of a different array object
    that happens to immediately follow the first array object in
    the address space.

with a footnote:

    Two objects can be adjacent in memory because they are adjacent
    elements of a larger array or adjacent members of a structure
    with no padding between them, or because the implementation
    chose to place them so, even though they are unrelated. If prior
    invalid pointer operations (such as accesses outside array
    bounds) produced undefined behavior, subsequent comparisons
    also produce undefined behavior.

The idea, I think, is that without that paragraph, given something like
this:

#include 
int main(void) {
    struct {
        int a[10];
        int b[10];
    } obj;

    printf("obj.a+10 %s obj.b\n",
           obj.a+10 == obj.b ? "==" : "!=");
}

the compiler would have to go out of its way to treat obj.a+10 and obj.b
as unequal.  (The output on my system is "obj.a+10 == obj.b", but the
pointers could be unequal if there's padding between a and b -- which is
unlikely.)

(I reported a relevant bug in gcc, where for objects that happen to be
adjacent the addresses are reported as unequal with -O1 or higher; the
gcc maintainers disagreed.
)

--
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
void Void(void) { Void(); } /* The recursive call of the void */

--- SoupGate-Win32 v1.05
 * Origin: you cannot sedate... all the things you hate (1:229/2)

<< oldest | < older | list | newer > | newest >> ]


(c) 1994,  bbs@darkrealms.ca