3 ms·
It's because memset is a standard function and has a defined standard way of acting, with the most important part being that it doesn't produce any side-effects
by DSMan195276 12y ago
It's because memset is a standard function and has a defined standard way of acting, with the most important part being that it doesn't produce any side-effects. It's also worth noting that accessing memory that's no longer in the current scope is undefined-behavior, so the compiler can assume it doesn't happen. Thus the memset has absolutely zero effect on the actual program and isn't necessary.
In general this isn't a big deal. It's only a big deal here because we're working on the assumption that you might have an issue in your code that invokes undefined-behavior and access contents of memory that you're not supposed to be looking at anymore, and the compiler's just assuming that your program won't ever allow that.
- pwg 12y agoWhat if one made some trivial use of the block of memory after having performed the memset, say something like this: void dosomethingsensitive(void) { uint8_t key[32]; ... /* Zero sensitive information. */ memset((volatile void *)key, 0, sizeof(key)); key[0] = key[1] + 1; } Would that thwart the optimizer, or would it also see through that usage and eliminate it as well?
- cperciva 12y agoThat just creates another dead store which will get eliminated.
- DSMan195276 12y agoYou should keep in mind that the memset call is almost guarenteed to be inlined. So your code actually looks like this: void dosomethingsensitive(void) { uint8_t key[32]; /* ... */ int i; for (i = 0; i < 32; i++) key[i] = 0; key[0] = key[1] + 1; } Assuming the optimizer is sufficiently smart, then it'll remove that 'for' and it'll remove the addition after it in the same fashion.