------- Comment #8 from brian at dessent dot net 2008-09-18 09:25 ------- Subject: Re: New: Loop incorrectly optimized to endless loop with -Os/-O2/-O3
I think this code is invalid. I seem to recall the argument that it's undefined behavior to increment or decrement a pointer to 0. Speaking of the binary addition and subtraction operators when applied to a pointer and integer constant, C99 6.5.6 #8 says that "If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. 6.3.2.3 #3 says that "[a null pointer] is guaranteed to compare unequal to a pointer to any object or function". Thus if the null pointer is the result of subtracting an integer constant from a pointer, it is undefined behavior because it cannot possibly be pointing to any valid object, let alone one that is within the allowed range in 6.5.6. So the compiler is allowed to assume that "--i" can never result in the null pointer in valid code, and optimizes away the test. -- http://gcc.gnu.org/bugzilla/show_bug.cgi?id=37569