use of memset and optimization

Tom Yu tlyu at MIT.EDU
Fri Nov 8 02:04:00 EST 2002

>>>>> "Sam" == Sam Hartman <hartmans at MIT.EDU> writes:

Sam> How does the compiler know that memset has no side effects
Sam> without cross-function optimization.  I agree that this could be
Sam> an issue for some compilers, I'm just surprised that gcc is smart
Sam> enough to optimize this.

gcc 3.x seems to have an inline memset() implementation if
optimization is active, so it *knows* all the side effects (only
writing to the specified memory) of calling memset.  Arguably, this
constitutes a cross-function optimization.

The key here is that it's a memset() of an automatic object that
immediately goes out of scope afterwards, ending the lifetime of the
object.  gcc knows that no access to the automatic object will occur
following the call to memset(), since it's undefined behavior to refer
to object outside of its lifetime.  See C99 section 6.2.4.  Some
experimentation suggests that the call to memset() may not be
optimized out by gcc if you're calling memset() on an object that
isn't automatic.


More information about the krbdev mailing list