[PATCH] memset 0 in obscure is optimized away by compiler
Harald Becker
ralda at gmx.de
Wed Apr 16 19:49:44 UTC 2014
Hi Tito !
>void getPassword(void)
>{
> char pwd[64];
>
> if (GetPassword(pwd, sizeof(pwd))) {
> /* checking of password, secure operations, etc */
> }
> memset(pwd, 0, sizeof(pwd));
> if (pwd[0] != '\0') {
> printf("memory not zeroed");
> exit(1)
> }
>}
>just out of curiosity and for me to learn, would code
>like this avoid optimization?
>or would the compiler see that we read just first char
>and zero only that and force us to check every
>char of pwd?
That depends on the compiler/optimizer. A simple optimizer just
sees pwd gets used and knows to zero pwd from memset. May be this
memset is not done by a function call, but shall result in
clearing the pwd array ... but on a higher optimizing system the
compiler may detect just reusage of pwd[0] and lack of access of
rest of pwd memory.
if you want to clean of memory, you shall not use auto variables
as in functions. Allocate your memory.
char *pwd = malloc(...); // or strdup
then do your job on pwd and finalize ...
memset(pwd, 0, size_pwd_allocated);
free(pwd);
Even if optimizer throws out the call to memset function the
compiler shall create code to fill the pwd array before it's
freed. Otherwise I consider the optimizer behaving wrong.
--
Harald
More information about the busybox
mailing list