format security warning

When -Wformat-security is enabled, I get a warning for:

  void foo(const char *x)
  {
     printf(x);
  }

which I expect since the format string isn’t a string literal, but I also get it for:

  static const char *fmt = “hello\n”;

  printf(fmt);

Granted the format string still isn’t a literal, but it is a known compile-time value and I don’t think I should get the warning for this case.

Is this a bug or intentional?

  Michael

When -Wformat-security is enabled, I get a warning for:

  void foo(const char *x)
  {
     printf(x);
  }

which I expect since the format string isn’t a string literal, but I also get it for:

  static const char *fmt = “hello\n”;

  printf(fmt);

Granted the format string still isn’t a literal, but it is a known compile-time value and I don’t think I should get the warning for this case.

Except it isn't... it's a non-const pointer to const data. If you make
it "static const char *const fmt", then the warning goes away.

David,

Thanks. You have a good point, but even though my pointer is non-const and could be changed, couldn’t the compiler see that it isn’t changed between the assignment and the printf call and still suppress the warning?

  Michael

David,

Thanks. You have a good point, but even though my pointer is non-const and could be changed, couldn’t the compiler see that it isn’t changed between the assignment and the printf call and still suppress the warning?

That would require potentially deeper analysis than is practical at
compile-time. But here's a way that it could break even though the
code doesn't change the value of 'fmt' between declaration and call.

const char **func() {
  static const char *fmt = "hello\n";
  printf(fmt);
  return &fmt;
}

int main() {
  *func() = "oh noes! %s";
  func();
}