aboutsummaryrefslogtreecommitdiffstats
path: root/printf.c
diff options
context:
space:
mode:
authorMarco Paland <marco@paland.com>2018-04-19 13:20:46 +0200
committerMarco Paland <marco@paland.com>2018-04-19 13:20:46 +0200
commitd74ad73009dd8ff4149a06904bb543f03a13f52e (patch)
tree8cf9a7323b6a82b2f404acedd959600d85e2734e /printf.c
parentdd8432003c9b4f352c053ef137c012d8ed50faf5 (diff)
downloadprintf-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.c19
1 files changed, 13 insertions, 6 deletions
diff --git a/printf.c b/printf.c
index d9384f7..3cc7aa2 100644
--- a/printf.c
+++ b/printf.c
@@ -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, ...)