Browse Source

AP_HAL: Util: make vsnprintf and snprintf always null-terminate

The C++ standard indicates these functions always return a
null-terminated string.  We should rename these functions if we're not
going to conform to the standards.

From https://en.cppreference.com/w/cpp/io/c/vfprintf :

"Writes the results to a character string buffer. At most buf_size-1
characters are written. The resulting character string will be
terminated with a null character"

We are still not standards-compliant in the case a length of 0 is passed
in, returning 0 where we should return the space that would be required
to store the formatted string.
mission-4.1.18
Peter Barker 7 years ago committed by Andrew Tridgell
parent
commit
33e3d6e254
  1. 7
      libraries/AP_HAL/Util.cpp

7
libraries/AP_HAL/Util.cpp

@ -52,9 +52,12 @@ int AP_HAL::Util::snprintf(char* str, size_t size, const char *format, ...) @@ -52,9 +52,12 @@ int AP_HAL::Util::snprintf(char* str, size_t size, const char *format, ...)
int AP_HAL::Util::vsnprintf(char* str, size_t size, const char *format, va_list ap)
{
BufferPrinter buf(str, size);
if (size == 0) {
return 0;
}
BufferPrinter buf(str, size-1);
print_vprintf(&buf, format, ap);
// null terminate if possible
// null terminate
int ret = buf._offs;
buf.write(0);
return ret;

Loading…
Cancel
Save