Just a sample of the Echomail archive
COMPLANC:
[ << oldest | < older | list | newer > | newest >> ]
|  Message 242,686 of 243,097  |
|  James Kuyper to highcrew  |
|  Re: On Undefined Behavior  |
|  01 Jan 26 17:49:40  |
 
From: jameskuyper@alumni.caltech.edu
On 2026-01-01 16:54, highcrew wrote:
> Hello,
>
> While I consider myself reasonably good as C programmer, I still
> have difficulties in understanding undefined behavior.
> I wonder if anyone in this NG could help me.
>
> Let's take an example. There's plenty here:
> https://en.cppreference.com/w/c/language/behavior.html
> So let's focus on https://godbolt.org/z/48bn19Tsb
>
> For the lazy, I report it here:
>
> int table[4] = {0};
> int exists_in_table(int v)
> {
> // return true in one of the first 4 iterations
> // or UB due to out-of-bounds access
> for (int i = 0; i <= 4; i++) {
> if (table[i] == v) return 1;
> }
> return 0;
> }
>
> This is compiled (with no warning whatsoever) into:
>
> exists_in_table:
> mov eax, 1
> ret
> table:
> .zero 16
>
>
> Well, this is *obviously* wrong. And sure, so is the original code,
> but I find it hard to think that the compiler isn't able to notice it,
> given that it is even "exploiting" it to produce very efficient code.
>
> I understand the formalism: the resulting assembly is formally
> "correct", in that UB implies that anything can happen.
> Yet I can't think of any situation where the resulting assembly
> could be considered sensible. The compiled function will
> basically return 1 for any input, and the final program will be
> buggy.
I agree.
> Wouldn't it be more sensible to have a compilation error, or
> at least a warning? The compiler will be happy even with -Wall -Wextra
> -Werror.
The rule that this code violates is still violated if an array is
accessed through a pointer, from a module which has no knowledge of the
actual length of the array. As a result, it does not make sense for the
standard to require diagnosis of all such violations.
However, implementations are free to diagnose violations such as this
one, where it would be perfectly feasible to do so. Whether or not
implementations actually do so is considered a matter of "Quality of
Implementation" (QoI), and therefore outside the scope of the standard.
Generating code that is only justified because the behavior is
undefined, and failing to diagnose the problem, seems to me to be very
bad QoI.
--- 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