Monday, December 14, 2009

C++98: Dangling Pointer

stringstream ss("MyString");const*p=ss.str().c_str(); makes p a dangling pointer. The invisible temporaries created from str() and c_str() live only until the last ';'.

It might look like it works, but if you add some more code following const*p=..., you may see your string corrupted. I just added stringstream ss2("Another String"); and this corrupted the data to which p points.

This kind of problem is fun (sarcasm, because it is not fun) to debug.

Reference: First-hand experience.

No comments:

Post a Comment