473,467 Members | 1,603 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

string/stringstream memory management

Im sorry for asking a question that is surely in the archives somewhere, but
I have been unable to locate it.

Its about string memory management. I need to dynamically construct a
C-style string and was planning to go about it this way;

char* foo()
{
std::stringstream ss;
ss << ...
std::string s = ss.str();
char* c = s.c_str();
return c;
}

void main()
{
char* c = foo();
// work with c
delete(c);
}

What am I doing wrong? Should I be deleting stuff somewhere? Will the foo
return a pointer to some out of scope memory - should it be;

char* foo()
{
std::stringstream* ss = new std::stringstream();
*ss << ...
std::string s = ss->str();
delete(ss);
char* c = s.c_str();
return c;
}

Am I deleting too much? ...

Thanks for any guidance you can offer.

El.
Jul 19 '05 #1
5 15872
Ellarco wrote:
Im sorry for asking a question that is surely in the archives somewhere, but
I have been unable to locate it.
This one is a classic -

Its about string memory management. I need to dynamically construct a
C-style string and was planning to go about it this way;
That usually means use of new

char* foo()
{
std::stringstream ss; ^^^^ defined automatic - life of object is life of function ss << ...
std::string s = ss.str(); ^^^^ defined automatic - life of object is life of function char* c = s.c_str(); ^^^^ s.c_str() did not copy or allocate new memory for this return c; ^^^^ Oops - returning a pointer to memory that is just about to be
deleted ...
}

void main()
{
char* c = foo(); ^^^^ c is pointing to memory that is unallocated // work with c
delete(c); ^^^^ trying to deallocate a pointer that is not allocated bad bad bad }

What am I doing wrong? Should I be deleting stuff somewhere? Will the foo
return a pointer to some out of scope memory - should it be;

char* foo()
{
std::stringstream* ss = new std::stringstream();
*ss << ...
std::string s = ss->str();
delete(ss); ^^^^ It's not your responsibility to delete this, s will do it when it
gets destroyed. char* c = s.c_str();
return c;
}

Am I deleting too much? ...
YEP.


Thanks for any guidance you can offer.

El.


Jul 19 '05 #2

"Ellarco" <no****@eircom.net> wrote in message news:55*************************@posting.google.co m...

char* c = s.c_str();
First, this shouldn't even compile. c_str() is returns const char*.

The return value of c_str() becomes invalid as soon as a non-const member
(including the destructor), get's invoked. S is destroyed as soon as the
function exits so the value returned is invalid by the time it reaches the
caller.

You could return a copy.
char* c = new char[s.size()+1];
strcpy(c, s.c_str());
return c;
void main()
main must return int.
delete(c);
Delete is not a function. You don't need the parens. Further,
Since your intent is that c points to an array allocation, the proper
delete is:
delete [] c;
std::stringstream* ss = new std::stringstream();
*ss << ...
std::string s = ss->str();
delete(ss);


This is just an elaborate way of doing the same thing you had before.
It's not the stringstream that was the problem, it was what you did with
the string called "s" afterwoard.

Why not just return a string. It's usually easier when you need a const char*
out of a string to just use c_str() at the last possible moment. Frequently, the
lifetime of ths string is such that you don't have to wory about making a copy
of the c_str() value because your string persists longer than the char* is needed.
Jul 19 '05 #3
no****@eircom.net (Ellarco) writes:
Im sorry for asking a question that is surely in the archives somewhere, but
I have been unable to locate it.

Its about string memory management. I need to dynamically construct a
C-style string and was planning to go about it this way;

char* foo()
{
std::stringstream ss;
use std::ostringstream
ss << ...
std::string s = ss.str();
char* c = s.c_str();
return c;
}
here, s goes out of scope and is destroyed - c points to never-neverland.
void main()
main returns int
{
char* c = foo();
// work with c
delete(c);
}


You can either create a new C-style string in foo() using strcpy(), or
you can (much preferable IMHO) just return a std::string from foo:

std::string foo() {
std::ostringstream ss;
ss << ...;
return ss.str();
}

If you insist on using C-style strings, create one with new[] in
foo, strcpy() to it, and delete[] it in main().

HTH & kind regards
frank

--
Frank Schmitt
4SC AG phone: +49 89 700763-0
e-mail: frankNO DOT SPAMschmitt AT 4sc DOT com
Jul 19 '05 #4


Ellarco wrote:

Im sorry for asking a question that is surely in the archives somewhere, but
I have been unable to locate it.

Its about string memory management. I need to dynamically construct a
C-style string and was planning to go about it this way;

char* foo()
{
std::stringstream ss;
ss << ...
std::string s = ss.str();
char* c = s.c_str();
return c;
}

Bad idea.
AT the moment this function terminates, the object s is killed.
And since the object s is killed, so is the buffer it handed out
to you through c_str().

void main()
int main()
{
char* c = foo();
// work with c
delete(c);


wrong syntax. Must be delete [] c;
Please: always cut and paste code, don't write it directly in your
newsreader. Otherwise we are hunting bugs which simply are not there
in your real program.

Well. Did you allocate something? Did your documentation of c_str()
tell you to delete the buffer?
The answer is no in both cases. So, no, you don't have to delete
anything (but that will change in a short while :-)

As you have seen, you can't return what c_str() gives to you, since
the object itself goes out of scope and hence the buffer is deleted,
while doing so. From this it follows that you first have to create
a copy of the C-style string:

char* foo()
{
....
std::string s = ss.str();

char* c = new char [ s.size() + 1 ];
strcpy( c, s.c_str() );
return c;
}

Now foo hands out a dynamically allocated buffer which is filled with
a copy of what c_str() handed out.
And since this buffer was allocated with new[], you have to delete[]
it somewhere.

int main()
{
char* cc = foo();
....
delete [] c;
}

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 19 '05 #5

"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:3F***************@gascad.at...


Ellarco wrote:

Im sorry for asking a question that is surely in the archives somewhere, but I have been unable to locate it.

Its about string memory management. I need to dynamically construct a
C-style string and was planning to go about it this way;

char* foo()
{
std::stringstream ss;
ss << ...
std::string s = ss.str();
char* c = s.c_str();
return c;
}


Bad idea.
AT the moment this function terminates, the object s is killed.
And since the object s is killed, so is the buffer it handed out
to you through c_str().

void main()


int main()
{
char* c = foo();
// work with c
delete(c);


wrong syntax. Must be delete [] c;
Please: always cut and paste code, don't write it directly in your
newsreader. Otherwise we are hunting bugs which simply are not there
in your real program.

Well. Did you allocate something? Did your documentation of c_str()
tell you to delete the buffer?
The answer is no in both cases. So, no, you don't have to delete
anything (but that will change in a short while :-)

As you have seen, you can't return what c_str() gives to you, since
the object itself goes out of scope and hence the buffer is deleted,
while doing so. From this it follows that you first have to create
a copy of the C-style string:

char* foo()
{
....
std::string s = ss.str();

char* c = new char [ s.size() + 1 ];
strcpy( c, s.c_str() );
return c;
}

Now foo hands out a dynamically allocated buffer which is filled with
a copy of what c_str() handed out.
And since this buffer was allocated with new[], you have to delete[]
it somewhere.

int main()
{
char* cc = foo();
....
delete [] c;
}

--
Karl Heinz Buchegger
kb******@gascad.at


Thanks to all. Youve cleared it up. To summarise what youve said, everything
is as normal. I had an idea in my head that string behaved in some sort of
anomalas (in terms of memory) way - idiot. Apologies for the buggy code I
posted, and thanks again.

El.
Jul 19 '05 #6

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

Similar topics

0
by: Richard Jones | last post by:
Garbage Collection & Memory Management Summer School 20-21 July 2004, Canterbury, UK The performance of today's memory-hungry applications depends on efficient dynamic memory management,...
11
by: Michael B. Allen | last post by:
Coming from C and Java on *nix I'm a little out of my element messing around with CList and MSVC++ but I think my issues are largely syntactic. I have an ADT that I use called a 'varray' that can...
1
by: Tony Selke | last post by:
Forgive my rather wide posting of this note, but I was uncertain of where I would find the best help. I am working on a class that is basically providing a secure location for name/value pairs...
2
by: DANIEL BEAULIEU J | last post by:
Basically i am a student taking an operating systems course which is c++ intensive. Familiar with Java, and so not so familiar with memory management. Looking for suggestions of exercises or web...
10
by: Segfahlt | last post by:
I have a fairly simple C# program that just needs to open up a fixed width file, convert each record to tab delimited and append a field to the end of it. The input files are between 300M and...
8
by: Chad | last post by:
hello, i am losing memory each time i make this call to a C++ dll (I make frequent calls). 'in VB.Net Declare Function grab Lib "grabber.dll" _ (ByRef lpBuf As Byte, ByVal lnum As Integer)...
1
by: trialproduct2004 | last post by:
Hi all, I am having slight confusion regarding memory management in .net. Say suppose i have two application one is in C# and other is in MFC(VC++). Both of this application are using lots...
0
by: erez_acount | last post by:
***************************************************************************** Call For Papers The 2006 International Symposium on Memory Management (ISMM'06) Co-located with PLDI 2006 ...
2
by: chris.ritchie | last post by:
My question is very basic, but I can't find any material on it. Compare these: string x; // only used within the following loop for (int y = 0; y < 10; y++){ x = toString(y); use(x); } ...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
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
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...
0
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...

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.