Path: csiph.com!news.swapon.de!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: Equal yet different pointers Date: Thu, 16 Nov 2017 11:36:20 -0800 Organization: None to speak of Lines: 52 Message-ID: <87wp2qxbgr.fsf@kst-u.example.com> References: <87k1yqyxgx.fsf@kst-u.example.com> <8760aaav4d.fsf@gmail.com> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: reader02.eternal-september.org; posting-host="c0732fd20b87a32d7f44c84be981d0b2"; logging-data="22752"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+0aGubMKD0b4HVrjRqM8Rx" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/25.1 (gnu/linux) Cancel-Lock: sha1:tyckeT33b3rpSys45hlO2FDKZrg= sha1:1m3d8ygdqARsq4bwtwK29no+RW4= Xref: csiph.com comp.lang.c:122754 Gareth Owen writes: > Keith Thompson writes: > >>> gcc /does/ do something wrong here - it accepts this program without >>> warnings, even with -Wall -Wextra. So I do have something to complain >>> about here with gcc. >> >> Why do you expect a warning? There may or may not be undefined >> behavior, but as far as I can tell no diagnostic is required. > > Because some people have expectations that extend beyond the C standard? > I appreciate that the holy standard (peace be upon it) is your sole > point of reference in all things, but most people quite like that GCC > sometimes give diagnostics for dangerous or undefined constructs, even > when the standard says they're not required. > > Its not unreasonable to expect one in a trivial case of UB like this. I was replying to David Brown; please don't snip attributions. I'm still curious why he expects a warning, and in particular whether he thinks one is required. I don't believe this is a trivial case of UB. I'm not even convinced that there's any undefined behavior. Again, here's the code: #include #include int main() { int i = 1; int j = 2; int * p = &i + 1; int * q = &j; if( !memcmp( &p, &q, sizeof( p ))) { *p = 3; printf( "%d %d\n", *p, *q ); }} p points just past the end of an object (which is treated as a 1-element array). Normally dereferencing such a pointer would have undefined behavior, but in this case it's done only after verifying that that pointer is bitwise equal to a pointer to another object. There are some sticky issues in the relationship between bitwise equality and pointer equality (which I'm glossing over for now), but aside from that I see no UB. Assuming the compiler takes advantage of the behavior of memcmp(), it might even be able to prove to itself that *p is valid, since p and q point to the same location and q is definitely a valid dereferenceable pointer. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"