Click here to Skip to main content
15,941,444 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Will the following piece of code cause memory leak?

#include <iostream>

using namespace std;

void someFunction(const char* str)
	cout << "buffer   :" << str << endl;
	std::string abc(str);
	abc = abc.substr(5);
	cout <<"After manipulation    :" <<endl;

	str = abc.c_str(); //will this create memory leak?

int  main()
	std::string str = "My file is this one";
	const char* c = str.c_str();
	cout << c << endl;
	return 0;

It won't leak - in C++ 98 the c_str() buffer is cleaned up when the object is destroyed and in C++ 11 it's a pointer to the internal representation of the string.

However there's a couple of things to remember:

- pointers returned by c_str() are invalidated by any operation that causes a write to the string
- don't write anything through the pointer
- don't cache the pointer

And a final thing: Only use c_str() to be compatible with libraries written in C. For everything else use std::string unless you really know what you're doing (although in that case you wouldn't be asking this question!)
Share this answer
//will this create memory leak?

Nope, but what's the purpose of that line?
Share this answer
Aswin Waiba 4-Dec-13 23:05pm    
a piece of code like that is present in our project. Don't really understand what it was trying to achieve though :(

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900