This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: strstream


> Hi, enclosed file is a strstream test program. The generated string 
> seems broken. Bug? Please let me know what should I do.

Thanks for your bug report. This is not a bug in gcc, but in your
code. The str() method of a strstream does not necessarily return a
null-terminated string. One way of correcting your program is to write

#include <strstream>
#include <string>

std::string str() {
  std::ostrstream oss;
  oss << "a :" << 1 << std::endl;
  oss << "ab :" << 2 << std::endl;
  oss << "abc :" << 3 << std::endl;
  oss << "abcd :" << 4 << std::endl;
  oss << "a :" << 5 << std::endl;
  oss << "ab :" << 6 << std::endl;
  oss << "abc :" << 7 << std::endl;
  oss << "abcd :" << 8 << std::endl;
  oss << "a :" << 9 << std::endl;
  oss << "ab :" << 10 << std::endl;
  oss << "abc :" << 11 << std::endl;
  oss << "abcd :" << 12 << std::endl;
  return std::string(oss.str(),oss.pcount());
}

int main() {
  std::cout << str() << std::endl;
  std::cout << str() << std::endl;
  std::cout << str() << std::endl;
  return 0;
}

Another approach is to write the std::ends manipulator onto the
strstream, which makes the resulting string null-terminated.

Hope this helps,
Martin


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]