Certain pointer operations may result in undefined behavior:
int main()
{
int arr[4] = {0, 1, 2, 3};
int * p = arr + 5; // undefined behavior
}
In short, you can't assume that result will be placed after the array. What if result is optimized to a register? It actually sounds quite likely to me given the tight loop. int main(int argc, char ** argv)
{
int arr[4] = {0, 1, 2, 3};
int * p = arr + 5; // valid
*p; // undefined behavior
return 0;
}"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."
That is, if either P or P+N don't point to the same array object, or one past the end of the array object, the result is undefined. Thus,
int arr[4] = {0, 1, 2, 3};
... arr + 4 ... // OK, points to one past the end of the array object
... arr + 5 ... // undefined
I'm sure the C standard is the same.6.5.6.8 from ISO/IEC 9899:201x draft of March 1, 2009:
...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....
As for this particular example, result is allocated on the stack and is guaranteed to not lie within s, so the gcc optimization is perfectly safe.
It might seem silly in this example, but as soon as I change the program to a very similar one:
void sum2(const unsigned char *s, unsigned char *result) {
*result = 0;
for (size_t i=0; i < strlen(s); i++) {
*result += s[i];
}
}
It cannot be optimised in the same way anymore (gcc won't) because you can't guarantee memory areas pointed at by arguments don't overlap.This is wrong. Attempting to use random pointers to outside of what your compiler and malloc allocated is undefined.
And indeed, aliasing issues like in your example will prevent gcc from optimizing out excess strlen; it can only do so if it can prove that both global memory and the buffer passed to strlen have not been modified. Local variables and return values cannot alias anything, and part of the guarantee of pure functions like strlen is that they have no side effects.