Optimisations and undefined behaviour

Jeff Law law@redhat.com
Mon Nov 9 22:11:00 GMT 2015


On 11/09/2015 02:59 PM, Vincent Lefevre wrote:
> On 2015-11-09 14:29:25 +0000, Andrew Haley wrote:
>> Here it is again:
>>
>> int foo(int x) {
>> 	if (x > 1290) {
>> 		printf("X is wrong here %d, but we don't care\n", x);
>> 	}
>> 	return x*x*x;
>>
>> Here, the printf writes to a stream then the UB happens.  But the
>> stream is buffered and the UB kills the process before the stream is
>> flushed.  There is nothing in the C specification to prevent this, and
>> neither should there be.  I don't think it's even possible.
>
> But it may happen that the buffer is full, so that the stream will
> be flushed and the printf can block forever (e.g. is the user pipes
> the output to a process that doesn't read anything) so that the
> "return x*x*x;" is not reacheable for this particular instance.
> So, in this case, the UB never happens.
Precisely.  And if the UB never happens, our license to do strange and 
interesting things is revoked :-)

I feel it's best to err on the side of safety here -- given a function 
call, loops and the like, we have to consider the possibility that the 
statement which exhibits UB may not be executed.  And until that 
statement is executed, we have no license to do anything weird.

That's precisely why the path isolation code operates in the manner in 
which is does.

jeff



More information about the Gcc-help mailing list