From 69f5ba17eef319bc112cadd54f18cccc10495ecb Mon Sep 17 00:00:00 2001 From: Karen Arutyunov Date: Wed, 17 Oct 2018 13:04:52 +0300 Subject: Fix undefined behavior for ofdstream::write(nullptr, 0) --- libbutl/fdstream.cxx | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) (limited to 'libbutl/fdstream.cxx') diff --git a/libbutl/fdstream.cxx b/libbutl/fdstream.cxx index 955b75d..72439ae 100644 --- a/libbutl/fdstream.cxx +++ b/libbutl/fdstream.cxx @@ -306,7 +306,14 @@ namespace butl size_t an (epptr () - pptr ()); // Amount of free space in the buffer. if (n <= an) { - memcpy (pptr (), s, n); + assert (s != nullptr || n == 0); + + // Note that the memcpy() function behavior is undefined if either of + // pointers is NULL, even if the bytes count is zero. + // + if (s != nullptr) + memcpy (pptr (), s, n); + advance (n); return n; } @@ -361,7 +368,13 @@ namespace butl an = 0; else { - memcpy (pptr (), s, an); + assert (s != nullptr || an == 0); + + // The source can not be NULL (see above for details). + // + if (s != nullptr) + memcpy (pptr (), s, an); + advance (an); } @@ -398,7 +411,13 @@ namespace butl // if (n <= static_cast (epptr () - pbase ())) { - memcpy (pbase (), s, n); + assert (s != nullptr || n == 0); + + // The source can not be NULL (see above for details). + // + if (s != nullptr) + memcpy (pbase (), s, n); + advance (n); return sn; } -- cgit v1.1