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

kdevel <[email protected]> changed:

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

--- Comment #3 from kdevel <[email protected]> ---
(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;
}

--

Reply via email to