Hacker News new | ask | show | jobs
by pascal_cuoq 4306 days ago
> Is the compiler still allowed to optimize away the zeroing in this case?

Yes, completely. In the snippet below, the compiler is allowed to eliminate all code after “leave secrets in array c”.

  {
    char c[2];
    ... /* leave secrets in array c */
    memset(c, 0, 2);
    c[0] = 0;
    c[1] = 0;
    memset(c, 0, 2);
    if (c[0] || c[1]) exit 1;
  }
The compiler is also allowed to compile the last three instructions below as if they were “return 0;”

  {
    char c[2];
    ... /* leave secrets in array c */
    c[0] = 0;
    c[1] = 0;
    return c[0] + c[1];
  }
1 comments

> In the snippet below, the compiler is allowed to eliminate all code after “leave secrets in array c”

gcc 4.4.5 doesn't though (-O3), it still clears the stack once and performs the comparison.

I believe these optimizations can be defeated by declaring a global

  volatile char fill = 0;
and using that instead of 0 in memset().
It's not guaranteed to defeat the optimization. For instance, it could just read fill into two registers and do the comparison there.