Hi,

I recently read that memory leaks can occur when using the string stream str() member function (http://www.troubleshooters.com/codecorn/memleak.htm). Is this true only for passing pointers or references to the created string object? Is this true at all?

For example, can anyone see if the following code would cause a leak if the first open function is called?

short SerialPort::open(int portNum, const string &settings){
   stringstream deviceName;
   
   deviceName << "\\\\.\\COM" << portNum;    // weird \\.\ allows emulated ports to work
   
   return open(deviceName.str(), settings);
   }

short SerialPort::open(const string &deviceName, const string &settings){
   cout << "SerialPort::open()" << endl;
   
	hComm = CreateFile(deviceName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

   DCB dcb;

// the following commented lines have been abbreviated
//GetCommState(hComm, &dcb)
//BuildCommDCB(settings.c_str(), &dcb)
//SetCommState(hComm, &dcb)
//SetCommTimeouts(hComm, &timeouts)

   cout << "Serial Port " << deviceName << " opened OK" << endl;
	return 0;
   }

Thanks for any insight!
-Doug

The page appears to be over 10 years old, and the information probably older than that. Standard C++ does not have a class called ostrstream, and, to my knowledge, the standard C++ stringstream facility does not leak.

>I recently read that memory leaks can occur when
>using the string stream str() member function
You're mixing up two different classes: strstream and stringstream. The former is an ancient class that was part of the old iostream library and should be avoided because it was hard to use correctly. The latter is the standard replacement for it which is hard not to use correctly.

Thanks guys, that's very encouraging indeed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.