[PATCH] memset 0 in obscure is optimized away by compiler

Cathey, Jim jcathey at ciena.com
Wed Apr 16 19:38:32 UTC 2014


>  char pwd[64];
>
>  memset(pwd, 0, sizeof(pwd));
>  if (pwd[0] != '\0') {
>	printf("memory not zeroed");

>or would the compiler see that we read just first char
>and zero only that and force us to check every
>char of pwd?

If CC knows what memset does (and I believe they
generally do these days), _none_ of the code above
will be left after optimization.  That's the whole
point of lifetime analysis in a code optimizer.

Source code that is depending upon side-effects is
broken.  If, as in the original case, you are intending
that a free'd buffer be zeroed by application code
as a debugging aid, you _must_ teach the compiler that
it cannot 'know' what free does, else its optimizer is
entirely justified in eliminating the zeroing code.
Either declare (cast?) the buffer as volatile, eliminate
the smarts associated with the free function, or put
the clearing in a separate function outside of the
scope of the C compiler optimizer's reach.

Or, best yet, rebind the free function to one that
clears its buffer before returning it to the pool.
That's what you really wanted anyway.

-- Jim



More information about the busybox mailing list