Hacker News new | ask | show | jobs
by BananaaRepublik 1146 days ago
By the way, I realized that sprintf can be used to concatenate by using the buffer within the formatting itself, while snprintf prevents it. Is it a safety issue too?

  strcpy(buf, "foo");
  sprintf(buf, "%s%s", buf, "bar"); //buf contains "foobar"

  strcpy(buf, "foo");
  snprintf(buf, sizeof buf, "%s%s", buf, "bar"); //buf contains "bar"
1 comments

keep in mind that you can't do that, here's a quote that explains it well:

Some programs imprudently rely on code such as the following

    sprintf(buf, "%s some further text", buf);
to append text to buf. However, the standards explicitly note that the results are undefined if source and destination buffers overlap when calling sprintf(), snprintf(), vsprintf(), and vsnprintf(). Depend‐ ing on the version of gcc(1) used, and the compiler options employed, calls such as the above will not produce the expected results.

The glibc implementation of the functions snprintf() and vsnprintf() conforms to the C99 standard, that is, behaves as described above, since glibc 2.1. Until glibc 2.0.6, they would return -1 when the output was truncated.

- printf(3), Linux man-pages 6.04, 2023-04-01