Archived

This topic is now archived and is closed to further replies.

Help std::string

This topic is 5576 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I am trying to return a std::string that is larger than 15 chars in length. When it is larger it will crash b/c of a heap error. If the string is less than that, it is fine. Here is the function: std::string bc::Mapping::Map:rintInfo() { char* buf = new char[20]; sprintf( buf, "x1:%f, y1:%f, x2%f, y2:%f", x1, y1, x2, y2 ); std::string s = buf; return s; } Any ideas? Thanks

Share this post


Link to post
Share on other sites
Use a stringstream instead:


  std::string bc::Mapping::Map::PrintInfo()
{
std::ostringstream ss;

ss << "x1: " << x1 << ", "
<< "y1: " << y1 << ", "
<< "x2: " << x2 << ", "
<< "y2: " << y2;

return ss.str();
}


No guarantees that''ll compile since it''s off the top of my head.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
char* buf = new char[20];

Maybe 20 isn''t enough, and you forgot to delete the memory allocated here.

Share this post


Link to post
Share on other sites
the reason it''s crashing is because that string is _much_ longer than 20 characters (19 + 1 null). Two suggestions:
- use strstream as suggested, although formatting with it can be tricky
- allocate something like 4096 bytes to your stack char array. Stack is cheap (usually--if you''re on an embedded platform, disregard).

Share this post


Link to post
Share on other sites
Actually, I just realized you''re NOT using the stack, you''re dynamically allocating a buffer and then not freeing it. This will leak 20 bytes every time you call it, and 20 bytes isn''t nearly enough. If you''re not going to use strstream, make it a stack-allocated buffer and increase its size.

Share this post


Link to post
Share on other sites