diff options
| author | Marco Paland <marco@paland.com> | 2018-04-19 13:20:46 +0200 | 
|---|---|---|
| committer | Marco Paland <marco@paland.com> | 2018-04-19 13:20:46 +0200 | 
| commit | d74ad73009dd8ff4149a06904bb543f03a13f52e (patch) | |
| tree | 8cf9a7323b6a82b2f404acedd959600d85e2734e /printf.c | |
| parent | dd8432003c9b4f352c053ef137c012d8ed50faf5 (diff) | |
| download | printf-d74ad73009dd8ff4149a06904bb543f03a13f52e.tar.gz printf-d74ad73009dd8ff4149a06904bb543f03a13f52e.tar.bz2 printf-d74ad73009dd8ff4149a06904bb543f03a13f52e.zip | |
fix(printf): fix snprintf buffer termination
Fixes #7 (partly)
Diffstat (limited to 'printf.c')
| -rw-r--r-- | printf.c | 19 | 
1 files changed, 13 insertions, 6 deletions
| @@ -355,13 +355,13 @@ static size_t _vsnprintf(char* buffer, size_t buffer_len, const char* format, va    unsigned int flags, width, precision, n;
    size_t idx = 0U;
 -  while (idx < buffer_len) {
 -    // end reached?
 -    if (*format == (char)0) {
 -      buffer[idx] = (char)0;
 -      break;
 -    }
 +  // check if buffer is valid
 +  if (!buffer) {
 +    return 0U;
 +  }
 +  while ((idx < buffer_len) && *format)
 +  {
      // format specifier?  %[flags][width][.precision][length]
      if (*format != '%') {
        // no
 @@ -582,9 +582,16 @@ static size_t _vsnprintf(char* buffer, size_t buffer_len, const char* format, va      }
    }
 +  // termination
 +  if (buffer_len > 0U) {
 +    buffer[idx == buffer_len ? buffer_len - 1U : idx] = (char)0;
 +  }
 +
 +  // return written chars without terminating \0
    return idx;
  }
 +
  ///////////////////////////////////////////////////////////////////////////////
  int printf(const char* format, ...)
 | 
