473,834 Members | 1,873 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2619
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********@gma il.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<c onst 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.co mwrote:
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::co py to put the string into it.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
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
22751
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 the std::string a pointer and a length and then give the std::string control over the pointer and its content? I'm basically trying to avoid copying large text between an std::string and a char pointer, and vice versa. Is there anyhing in the...
12
2035
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 information. I know that C++ strings are supposed to be the "right" way to handle strings but I suspect that converting "char *" to string
4
3436
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" system call. string buf(1024); int fd; write(fd,(void *)(&buf),buf.size());
0
3947
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. It is almost like it is trying to implement it's own COM interfaces... below is the header, and a link to the dll+code: Zip file with header, example, and DLL:...
9
10171
by: kiran.agashe | last post by:
Hi, Please refer program below: #include <string> #include <cstdio> using namespace std; const char* f(); main() {
34
31336
by: Perro Flaco | last post by:
Hi! I've got this: string str1; char * str2; .... str1 = "whatever"; .... str2 = (char *)str1.c_str();
6
69846
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
2488
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; ofstream editFile; editFile.open (name, ios::out | ios::app);
10
11342
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");
1
10548
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10219
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7758
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6954
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5627
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5794
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4427
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3978
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3081
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.