Hi,

I found a bug in the result of std::vsnprintf(), here is the test app that can 
reproduce it.
I tested with g++ 11.2 and 12.2 and both have the bug,  and this issue does not 
happen with visual c++.

#include <stdio.h>
#include <string>
#include <iostream>
#include <cstdarg>

int Sprintf(std::string& s, const char* pszFormat, ...) {
  va_list argptr;
  va_start(argptr, pszFormat);

  auto n = std::vsnprintf(nullptr, 0, pszFormat, argptr);
  char* buf = (char*)malloc(n + 1);
  n = std::vsnprintf(buf, n + 1, pszFormat, argptr);
  s = buf;
  free(buf);

  va_end(argptr);
  return n;
}

int main() {
  std::string s, s0, s1, s2;
  double d = 3.14;

 //the result is wrong
  Sprintf(s, "abc%.0f", d);
  std::cout << "s=" << s << "\n\n";

 //the result is wrong
  Sprintf(s0, "%.0f", d);
  std::cout << "s0=" << s0 << "\n\n";

  //the printf result is correct
  printf( "%.0f\n\n", d);

  //now it becomes correct
  Sprintf(s1, "%.0f", d);
  std::cout << "s1=" << s1 << "\n\n";

 //and this becomes correct too.
  Sprintf(s2, "abc%.0f", d);
  std::cout << "s2=" << s2 << "\n\n";
}


In a short word, printf() get the correct result, after calling it, vsnprintf() 
became correct too.

my build command:   g++ -o  t1  t1.cpp

Thanks,
Qiang Ren





Reply via email to