473,609 Members | 1,868 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning String Literals from a function

Hi all...

What's the best way to return some string from a function (without
using the string class). Would the following work:

char* getString( )
{
return "TheString" ;
}

I've seen this in code in a lot of places, but I would have thought the
string literal in the function would be allocated on the stack, a
pointer to the string will be returned, and the block of memory holding
the string would be deallocated when the function returns... Would it
make a difference if the return type was const char* ?

If this doesn't work, the only other way I can think of is to either
dynamically allocate a new string in the function (in which case it
wouldn't be clear to the user to delete it), or to make them pass a
reference to a string and strcpy "TheString" into it (which I find
annoying)... Is there any other way?

Jul 25 '06 #1
6 10947

Siam wrote:
Hi all...

What's the best way to return some string from a function (without
using the string class). Would the following work:

char* getString( )
{
return "TheString" ;
}

I've seen this in code in a lot of places, but I would have thought the
string literal in the function would be allocated on the stack, a
pointer to the string will be returned, and the block of memory holding
the string would be deallocated when the function returns... Would it
make a difference if the return type was const char* ?
Don't worry, the code is fine. The string literal itself is stored
globally, the function just returns a pointer to that global location.
Returning const char* would be better though, as the returned string
should not be modified by the caller.

Jul 25 '06 #2
Siam posted:
Hi all...

What's the best way to return some string from a function (without
using the string class). Would the following work:

char* getString( )
{
return "TheString" ;
}

Put a "const" in there:

char const *GetStr()
{
return "Hello";
}

If it helps your understanding, you could think of the snippet above as
being equivalent to:

char const str[] = "Hello";

char const *GetStr()
{
return str;
}

You can see that you're simply returning the address of a global object --
so no memory is leaked, and no object is accessed after having being
destroyed.

--

Frederick Gotham
Jul 25 '06 #3
Cheers.. One more question.. Would the following code be alright?

char* getString( )
{
string s = "TheString" ; //using string class
return s.c_str();
}

Does c_str() create a global string literal and return its address, or
is this one allocated on the stack?

Cheers :)

Siam

Jul 25 '06 #4
Siam wrote:
Cheers.. One more question.. Would the following code be alright?

char* getString( )
{
string s = "TheString" ; //using string class
return s.c_str();
}
No, most certainly not.
Does c_str() create a global string literal and return its address, or
is this one allocated on the stack?
Unknown. It's magic. But in your case 's' is still a local object, and
it's destroyed when the fucntion ends. Whatever 'c_str' returns is tied
to that object, so the pointer you get is invalid as soon as the function
returns.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 25 '06 #5

Siam wrote:
Cheers.. One more question.. Would the following code be alright?

char* getString( )
{
string s = "TheString" ; //using string class
return s.c_str();
}
Does c_str() create a global string literal and return its address, or
is this one allocated on the stack?
No you can't do this. In your string class example above the global
literal "TheString" gets copied into some memory managed by the
std::string s , c_str() then returns a pointer to this memory
(technically it might be a copy again, but let's ignore that
complexity), but once you return from the function the std::string s
goes out of scope, and the memory it manages is effectively lost. Hence
any attempt to use the return from this function will likely blow up in
your face.

Jul 25 '06 #6
Siam posted:
char* getString( )

Stop using "pointer to non-const" to store the address of a string literal --
it's sloppy. The following code demonstrates:

char *PoorlyWrittenF unction()
{
return "I'm a string literal, and am inherently const, "
"even though the C type system doesn't acknowledge"
"it.";
}

int main(void)
{
*PoorlyWrittenF unction() = 'e';
}
The above code compiles without error, but invokes undefined behaviour
nonetheless.

--

Frederick Gotham
Jul 25 '06 #7

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

Similar topics

17
14333
by: Olivier Bellemare | last post by:
I've tried to make a function that returns the middle of a string. For example: strmid("this is a text",6,4); would return "is a". Here is my code: char *strmid(char *texte, int depart, int longueur) { char *resultat = " "; char *temporaire = " "; int nbr;
7
4352
by: al | last post by:
char s = "This string literal"; or char *s= "This string literal"; Both define a string literal. Both suppose to be read-only and not to be modified according to Standard. And both have type of "const char *". Right? But why does the compiler I am using allow s to be modified, instead of generating compile error?
7
2307
by: wonderboy | last post by:
Hey guys, I have a simple question. Suppose we have the following functions:- //-----My code starts here char* f1(char* s) { char* temp="Hi"; return temp;
19
2484
by: Robert Smith | last post by:
I am wondering why it is possible to return a pointer to a string literal (ie. 1) but not an array that has been explicitly allocated. (ie. 2) ? Both would be allocated on the stack, why does the first one not cause a compiler warning? #include <stdio.h> char * funca() { char *a = "blah"; //1 - ok // char a = "blah"; //2 - not ok
19
3093
by: Manish Tomar | last post by:
Hi All, The following code as per my knowledge should not work: int* some() { int b = 10; return &b; }
47
2310
by: pkirk25 | last post by:
I've made a small program to demonstrate one problem I'm having fixing strings in C. I need to be able to remove HTML mark-ups from text lines. I create my variable, pass it to my function, verify that the data has been passed correctly and then cannot get the data back! If I change the return to some random string literal, it comes back fine.
36
2254
by: MC felon | last post by:
how do we return strings or arrays from a function? i tried.. char some_func() //where i thought char would tell the compiler that the return is a string { char str; //something; return str; }
5
2888
by: polas | last post by:
Good morning, I have a quick question to clear up some confusion in my mind. I understand that using a string literal in a declaration such as char *p = "string literal" declares a pointer to memory holding the string and the string might very well be held in read only memory. However, I am sure that I read somewhere that the declaration char a = "string literal", even though a is an array (and I understand the differences between...
8
2209
by: darren | last post by:
Hi everybody, have a quick look at this code: ===== ===== int main(void) { string msg; makeString(msg); cout << "back in main, result = " << msg << endl;
0
8579
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
8555
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...
1
8232
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
8408
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
6064
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
5524
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
4098
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2540
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
1
1686
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.