sprintf may write beyond the buffer passed, snprintf is the safer option.
Recent Clang compiler by default warns on the use of sprintf (deprecated) for the c++ part of LDC. It'd be good to also remove it from D code. The fix is usually not so hard.
Comment #1 by dlang-bot — 2023-01-30T14:39:46Z
@RazvanN7 updated dlang/dmd pull request #14854 "Fix Issue 23658 - replace uses of sprintf with snprintf in the compiler" fixing this issue:
- Fix Issue 23648 - replace uses of sprintf with snprintf in the compiler
https://github.com/dlang/dmd/pull/14854
Comment #2 by dlang-bot — 2023-02-03T09:24:07Z
dlang/dmd pull request #14854 "Fix Issue 23648 - replace uses of sprintf with snprintf in the compiler" was merged into master:
- 3c51a0c69e4796fb6a29bc08a1be5207b8d66d1f by RazvanN7:
Fix Issue 23648 - replace uses of sprintf with snprintf in the compiler
https://github.com/dlang/dmd/pull/14854
Comment #3 by kdevel — 2023-02-06T08:12:33Z
(In reply to johanengelen from comment #0)
> sprintf may write beyond the buffer passed, snprintf is the safer option.
The origininal problem was writing beyond the buffer. By replacing sprintf with snprintf the problem now is truncation which goes unnoticed. Why not detect and throw if truncation occurs?
import core.stdc.stdarg;
extern (C) size_t snprintf_without_silent_truncation (char *s, size_t len, const char *fmt, ...)
{
import std.exception;
import std.stdio;
import std.format;
va_list args;
va_start (args, fmt);
auto rc = vsnprintf (s, len, fmt, args);
va_end (args);
enforce (rc >= 0, "vsnprintf failed");
enforce (rc < len, format!"vsnprintf: tried to write %d B + \\0 into buffer of size %d B" (rc, len));
return rc;
}
Comment #4 by razvan.nitu1305 — 2023-07-10T11:07:50Z
The bug report has been closed because the initial claim has been resolved. Please do not reopen bug reports, instead file new ones.
However, for this particular case I don't think that is necessary since underflow is not an issue.