Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

If you've managed to embed an integer into your char array and you are using that integer as an accumulator, you're probably "doing it wrong", very wrong. More to the point, you've got bigger problems than gcc's optimization specifics.

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.



I'm not saying this is useful for anything - I'm just asking about correctness of such optimisation. You can set the pointer to any address, which includes future stack. Also, nothing can 'lie within a pointer' really... - it might be inside an array.

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.


> You can set the pointer to any address, which includes future stack.

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.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: