Help std::string

Started by
6 comments, last by madfisher 21 years, 7 months ago
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
Advertisement
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.
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
char* buf = new char[20];

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).
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.).
char a[99999],*p=a;int main(int c,char**V){char*v=c>0?1[V]:(char*)V;if(c>=0)for(;*v&&93!=*v;){62==*v&&++p||60==*v&&--p||43==*v&&++*p||45==*v&&--*p||44==*v&&(*p=getchar())||46==*v&&putchar(*p)||91==*v&&(*p&&main(0,(char**)(--v+2))||(v=(char*)main(-1,(char**)++v)-1));++v;}else for(c=1;c;c+=(91==*v)-(93==*v),++v);return(int)v;}  /*** drpizza@battleaxe.net ***/
Thanks, I misspoke (er--miswrote?)

This topic is closed to new replies.

Advertisement