Remix.run Logo
kazinator 2 hours ago

sprintf can be safely used.

- For some conversions, you can establish an upper bound on how many characters they will produce. E.g. a positive decimal integer not more than 9999 does not consume more than four characters.

- It's possible to specify truncation. e.g. "%.64s" prints at most 64 characters from the string argument.

- There are enirely static cases that can be worked out at compile time, e.g.

  char big_enuf_buf[BIG_ENUF_BUF_SIZE];
  sprintf(big_enuf_buf, "%x-%04x-%04x", MAJOR, MINOR, BUILD); // preprocessor constants
Even if the buffer isn't big enough, and the behavior is formally undefined, it is entirely analyzable at compile time and we have support for that: the compiler can work out that the conversion needs, e.g., 13 bytes, including null termination, but the buffer only has 12.

The reasons for analyzing to it wouldn't necessarily just be for diagnostics, but possibly for compiling it down to a literal:

  char big_enuf_buf[BIG_ENUF_BUF_SIZE] = "A1-0013-000A";