473,834 Members | 2,255 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

return my_ostringstrea m.str().c_str() ;

63 New Member
I want to use a stringstream internally, but to conform to an api I want to return a char*.

Only this does not work:

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. using namespace std;
  5.  
  6. class A
  7. {
  8.     ostringstream my_ostringstream;
  9. public:
  10.     void generate()
  11.     {
  12.         my_ostringstream << "do something";
  13.     }
  14.     const char* get()
  15.     {
  16.         return my_ostringstream.str().c_str();
  17.     }
  18. };
  19.  
  20. void main()
  21. {
  22.     A a;
  23.     a.generate();
  24.     cout << "data: " << a.get() << "\n";
  25. }
  26.  

using ms visual studio 2005 I get a "debug assertion failed! [...] _BLOCK_TYPE_IS_ VALID(pHead->nBlockUse)" at runtime.

Ok, so maybe my_ostringstrea m.str() creates a local copy and then returns a pointer to a local object? Is that the case? And anyways, can somebody give me a hint on how to resolve that?
Feb 25 '08 #1
6 3000
weaknessforcats
9,208 Recognized Expert Moderator Expert
Temporary objects go out of scope at the end of a statement so the pointers to them become garbage.

Just don't rely on a compiler temporary.

I changed your code to allow for a member variable.

Expand|Select|Wrap|Line Numbers
  1. class A
  2. {
  3.     stringstream my_ostringstream;
  4.     string temp;
  5. public:
  6.     void generate()
  7.     {
  8.         my_ostringstream << "do something";
  9.     }
  10.     const char* get()
  11.     {
  12.         temp = my_ostringstream.str();
  13.         return temp.c_str();
  14.     }
  15. };
  16.  
Feb 25 '08 #2
jabbah
63 New Member
I changed your code to allow for a member variable.
Ok, that works. thanks for that.


A related question: Is there a similar way if we are given a simple function instead of a class? for example:

Expand|Select|Wrap|Line Numbers
  1. const char* getadata()
  2. {
  3.   ostringstream my_ostringstream;
  4.   my_ostringstream << "do something";
  5.   return my_ostringstream.str().c_str();
  6. }
  7.  
Ok, I do understand that this implementation cant possibly work, since it suffers from the same deficiency as my initial post. However, what I want is to return a char* and not force the caller to delete the returned value.
Maybe, I guess, ... thats just not possible, right?
Feb 26 '08 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
Ok, I do understand that this implementation cant possibly work, since it suffers from the same deficiency as my initial post. However, what I want is to return a char* and not force the caller to delete the returned value.
Maybe, I guess, ... thats just not possible, right?
You would need to allocate memory on the heap for the char* string and copy the std::string to that memory. There is a string::copy() for that purpose.

Then return the allocated address. Later someone else can delete it.
Feb 26 '08 #4
jabbah
63 New Member
Later someone else can delete it.
That is, someone else *has* to delete it, right.
Feb 27 '08 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
Yes, they do.

Unless...

You use a smart pointer that knows when to delete itself.

There is an article (and template code) for a handle in the C/C++ HowTos forum article on Handle classes.
Feb 27 '08 #6
jabbah
63 New Member
thanks weaknessforcats
Feb 28 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

7
3584
by: Sims | last post by:
Hi, if i have a code const char * GetValue() { std::string szVectorValue = ...// get a std::string from the vector return szVectorValue.c_str(); }
8
2375
by: John Smith | last post by:
Hi, I'm writing a library in C++ which is supposed to be used by people using C. One function I have must return a string to users which is arbitrary length. The user must be able to use this string as "char *" so I was wondering if the following construct is safe: char *Func() { static string str;
9
2136
by: Ingo Nolden | last post by:
Hi there, I am writing c++ for some months now. I think I know the language now, but not yet all the tricky things of stl. For a kernel which is not using mfc I am writing a serialization. For some reasons I want to implement it on my own. One goal is to make it robust against version changes and corrupted files. That means, when an object cannot be deserialized, it should be skipped. The validity of the remaining document can be verified...
7
7103
by: C | last post by:
If I want to declare a function in a header file that returns a string, I always get an error (something complaining about a syntax error before an ')'). I have declared: #ifndef MYHEADER_H #define MYHEADER_H
6
17602
by: Laura D | last post by:
How can I identify a carriage return in C++? \r, \f, \0, \n, \t does not work. I have also tried !isprint(ch), iscntrl(ch), isspace(ch), etc....with no luck! I even poked around in the MSDN and found some code that MS claims will save a file in unix format and I cut and pasted into my program(and made changes to suit): ..... char ch; char temp="\0"; //Open the file for reading in binarymode. ifstream fp_read(filename.c_str(),...
18
6889
by: Martin Pöpping | last post by:
Hello, I´ve a problem with the follwing code lines: string line; ifstream myfile ("doorcoordinates.txt"); if (myfile.is_open()) { char str; char * pch;
22
3264
by: Michael Rasmussen | last post by:
Hi all, Not sure if this is OT? I have a function in a library written in C++ which returns a strdup(s.c_str()) to an application written i C. Running Valgrind on my C-application shows this results in memory leaks due to the c_str is never freed. Example:
5
9525
by: Jason | last post by:
Hi, I am having some trouble returning a string from a c++ dll. I tend to get junk data back and I am not sure of the method, my code so far: Function is declared in c++ dll 'Test' and exported like this: extern "C" __declspec( dllexport ) BSTR getbagstr(); extern "C" __declspec( dllexport ) BSTR getbagstr() { g.getbag()->setdisplaybag("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZ");
8
6325
by: puzzlecracker | last post by:
Any ideas what may cause that for the string class to core dump? #0 0x0018de92 in std::string::c_str () from /usr/lib/libstdc++.so.5
0
9796
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9642
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10782
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10500
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10213
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...
0
9323
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7753
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...
1
4422
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
3972
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.