473,394 Members | 1,722 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

using a char* pointer returned by c_str after a string has beendeallocated

I have a class of the type

class A
{
private:
std::string data;
.......
public:
const char* toString();
};

A::A(const char* s):data(s) {}
const char* A::toString() { return data.c_str();)

I have the following scenario in the code:

A* pObj = new A("New");
const char* str = A -toString();
............
............
delete pObj;
printf("The string representation of A is %s", str);

Now I know that the above code is probably wrong because I use the
char pointer returned by the c_str() function after the object
(containing a string member variable) has been deallocated. But I am
interested to know why. Is it because the c_str() returns the internal
char pointer of the string object? c_str() returns a null terminated
string which means that probably a copy of the internal char buffer
terminated with a null character is returned to the user. But if that
is the case, it should be the responsibility of the user to explicitly
deallocate the char pointer after it is not being used. But we don't
do it do we? So I am a bit confused about what exactly happens.
Dec 12 '07 #1
3 2595
C++Liliput wrote:
I have a class of the type

class A
{
private:
std::string data;
.......
public:
const char* toString();
};

A::A(const char* s):data(s) {}
const char* A::toString() { return data.c_str();)

I have the following scenario in the code:

A* pObj = new A("New");
const char* str = A -toString();
............
............
delete pObj;
printf("The string representation of A is %s", str);

Now I know that the above code is probably wrong because I use the
char pointer returned by the c_str() function after the object
(containing a string member variable) has been deallocated. But I am
interested to know why. Is it because the c_str() returns the internal
char pointer of the string object? c_str() returns a null terminated
string which means that probably a copy of the internal char buffer
terminated with a null character is returned to the user. But if that
is the case, it should be the responsibility of the user to explicitly
deallocate the char pointer after it is not being used. But we don't
do it do we? So I am a bit confused about what exactly happens.
The exact details are unimportant, what matters is data.c_str() returns
a pointer to a buffer owned by data. So when the object containing data
is deleted, data is destroyed and the buffer becomes invalid.

--
Ian Collins.
Dec 12 '07 #2
On Wed, 12 Dec 2007 09:47:29 +0200, C++Liliput <av********@gmail.com>
wrote:
[...]terminated with a null character is returned to the user. But if
that
is the case, it should be the responsibility of the user to explicitly
deallocate the char pointer after it is not being used. But we don't
do it do we? So I am a bit confused about what exactly happens.
If it was the responsibility of the user to deallocate the buffer the
return type of c_str() would have better been std::auto_ptr<const char*>.
That way it would have been obvious that ownership is passed to the
caller. If you don't get a smart pointer you can basically assume that
ownership is not passed to the caller (at least that's the rule I try to
follow; this might not be true for every function of course).

Boris
Dec 12 '07 #3
On Dec 12, 8:52 am, Ian Collins <ian-n...@hotmail.comwrote:
C++Liliput wrote:
I have a class of the type
class A
{
private:
std::string data;
.......
public:
const char* toString();
};
A::A(const char* s):data(s) {}
const char* A::toString() { return data.c_str();)
I have the following scenario in the code:
A* pObj = new A("New");
const char* str = A -toString();
............
............
delete pObj;
printf("The string representation of A is %s", str);
Now I know that the above code is probably wrong because I
use the char pointer returned by the c_str() function after
the object (containing a string member variable) has been
deallocated. But I am interested to know why. Is it because
the c_str() returns the internal char pointer of the string
object? c_str() returns a null terminated string which means
that probably a copy of the internal char buffer terminated
with a null character is returned to the user. But if that
is the case, it should be the responsibility of the user to
explicitly deallocate the char pointer after it is not being
used. But we don't do it do we? So I am a bit confused about
what exactly happens.
The exact details are unimportant, what matters is
data.c_str() returns a pointer to a buffer owned by data. So
when the object containing data is deleted, data is destroyed
and the buffer becomes invalid.
Right. It's a question of contract. In fact, in the case of
std::string, the contract is that the pointer returned by
c_str() is valid until the next non-const function is called,
and no longer. Just reading a character with [] can
(theoretically, at least, but also practically, with g++, for
example) invalid it.

If he needs the pointer for a longer period of time, he'll have
to arrange to allocate the memory himself somehow, and use
std::string::copy to put the string into it.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Dec 12 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
by: Espen Ruud Schultz | last post by:
Lets say I have a char pointer and an std::string. Is it possible to get a pointer to the std::string's "content" so that the char pointer can point to the same text? And vice versa; can I give...
12
by: Vaca Louca | last post by:
Hello, I write an ISAPI authentication module which uses Berkeley DB and want it to be as efficient as possible. Both ISAPI and BerkeleyDB use arrays of chars (char *) to pass and receive...
4
by: christopherlmarshall | last post by:
I have gotten in the habit of using strings to manage character buffers that I pass in to unix system calls. For example, suppose I want to create a character buffer to use with the "write"...
0
by: Lokkju | last post by:
I am pretty much lost here - I am trying to create a managed c++ wrapper for this dll, so that I can use it from c#/vb.net, however, it does not conform to any standard style of coding I have seen....
9
by: kiran.agashe | last post by:
Hi, Please refer program below: #include <string> #include <cstdio> using namespace std; const char* f(); main() {
34
by: Perro Flaco | last post by:
Hi! I've got this: string str1; char * str2; .... str1 = "whatever"; .... str2 = (char *)str1.c_str();
6
by: Gary Wessle | last post by:
Hi I have char buffer = "jackson"; how can I get the same effect by string name = "jackson"; char buffer = name; //will not work I tried conat_cast<char*(name.c_str());
15
by: rEvolution27 | last post by:
I'm a c++ newbie here, trying out some stuff and when I try to compile this: void create() { char name; cout << "Creating a new timetable /n Please type a name for this timetable"; cin >name;...
10
by: william | last post by:
#include <stdio.h> int main() { char *str=NULL; char x="today is good!"; printf("%s", str); str=strtok(x," "); if (str=="today") //<==here is line that confuses me printf("they equals!\n");
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.