Help std::string
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
Use a stringstream instead:
No guarantees that''ll compile since it''s off the top of my head.
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.
You''re allocating a buffer using new, but never freeing it using delete []. Why?
Helpful links:
How To Ask Questions The Smart Way | Google can help with your question | Search MSDN for help with standard C or Windows functions
Helpful links:
How To Ask Questions The Smart Way | Google can help with your question | Search MSDN for help with standard C or Windows functions
char* buf = new char[20];
Maybe 20 isn''t enough, and you forgot to delete the memory allocated here.
Maybe 20 isn''t enough, and you forgot to delete the memory allocated here.
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).
- 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).
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.
strstream?
No thanks. They''re a deprecated compatibility feature.
The header one wants is <sstream> and the class std::stringstream (etc.).
No thanks. They''re a deprecated compatibility feature.
The header one wants is <sstream> and the class std::stringstream (etc.).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement