[Issue 23648] Replace all sprintf with snprintf

d-bugmail at puremagic.com d-bugmail at puremagic.com
Mon Feb 6 08:12:33 UTC 2023


https://issues.dlang.org/show_bug.cgi?id=23648

kdevel <kdevel at vogtner.de> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|RESOLVED                    |REOPENED
         Resolution|FIXED                       |---

--- Comment #3 from kdevel <kdevel at vogtner.de> ---
(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;
}

--


More information about the Digitalmars-d-bugs mailing list