Monday, October 8, 2012

C++ Programming: The Danger of string::c_str()

Let us look at the following program:

#include <sstream>
#include <string>
#include <iostream>

using namespace std;

int main()
   stringstream s;

   s << "Hello";

   const char *p = s.str().c_str();

   cout << p << endl;

   string b = "World";

   cout << p << endl;

   return 0;

The output of the program is:


The second string b shares the same location used by the early retrun of s.str().c_str() and overwrites it. It is unsafe to store the pointer from string::c_str() and use it later because it is an internal location that can be reused by other string objects.

No comments:

Get This <