Path: csiph.com!3.us.feeder.erje.net!feeder.erje.net!news.linkpendium.com!news.linkpendium.com!news.snarked.org!border2.nntp.dca1.giganews.com!nntp.giganews.com!news.iecc.com!.POSTED.news.iecc.com!nerds-end From: Bart Newsgroups: comp.compilers Subject: Re: Bounds checking, Optimization techniques and undefined behavior Date: Wed, 8 May 2019 01:14:29 +0100 Organization: virginmedia.com Lines: 42 Sender: news@iecc.com Approved: comp.compilers@iecc.com Message-ID: <19-05-057@comp.compilers> References: <19-04-021@comp.compilers> <19-04-023@comp.compilers> <19-04-037@comp.compilers> <19-04-039@comp.compilers> <19-04-042@comp.compilers> <19-04-044@comp.compilers> <19-04-047@comp.compilers> <19-05-004@comp.compilers> <19-05-006@comp.compilers> <19-05-016@comp.compilers> <19-05-020@comp.compilers> <19-05-024@comp.compilers> <19-05-025@comp.compilers> <19-05-028@comp.compilers> <19-05-029@comp.compilers> <19-05-034@comp.compilers> <19-05-045@comp.compilers> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 8bit Injection-Info: gal.iecc.com; posting-host="news.iecc.com:2001:470:1f07:1126:0:676f:7373:6970"; logging-data="79199"; mail-complaints-to="abuse@iecc.com" Keywords: standards, errors Posted-Date: 07 May 2019 21:50:27 EDT X-submission-address: compilers@iecc.com X-moderator-address: compilers-request@iecc.com X-FAQ-and-archives: http://compilers.iecc.com In-Reply-To: <19-05-045@comp.compilers> Content-Language: en-GB Xref: csiph.com comp.compilers:2292 On 07/05/2019 10:04, David Brown wrote: > Just for a laugh, try this code: > #include > > int main(void) { > int i; > int j; > int *pi = &i; > int *pj = &j; > int sum = 0; > > printf("pi = %p, pj[-1] = %p\n", (void*) pi, (void*) &pj[-1]); > > for (i = 0; i < 11; i++) { > if (i == 3) { > pj[-1] = 5; > } > sum += i; > } > printf("Sum is %i\n", sum); > } This is the sort of code that /I/ would say has undefined behaviour. In this case because pj points to a 1-element block, and you writing outside that block. With my C compiler, it shows '55', whatever order i and j are defined in. That's because these int32 types are 64-bit aligned so have a 4-byte gap between. I could get '48' if I changed the ints to 64 bits. Translating to my language, and in the knowledge that the (64-bit) ints there are assigned consecutively, and knowing that j follows i, then I would expect a result of 48. I expect it because that's what I coded, and my compilers tend to do what I tell them in the language. If I wanted to do something underhand like this for some genuine reason, and which would be well-defined according to the provisos above, then I don't want to have to fight the compiler to achieve it. In that case, a compiler generating '55' would be undesirable.