Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is returning a string literal address from a function safe and portable?

Tags:

c++

string

I need a function to return a string that will only be accessed read-only. The string contents is known at compile time so that I will use a string literal anyway.

I can return something like std::string:

std::string myFunction()
{
   return "string";
}

or return const char*:

const char* myFunction()
{
   return "string";
}

Is the second alternative safe and portable in this scenario?

like image 399
sharptooth Avatar asked Mar 03 '10 13:03

sharptooth


People also ask

Can you return a string in a function?

Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string. All forms are perfectly valid. Note the use of const , because from the function I'm returning a string literal, a string defined in double quotes, which is a constant.

What is a string literal used for?

A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string. You must always prefix wide-string literals with the letter L.

What is difference between literal and string literal?

Character literals represents alphabets (both cases), numbers (0 to 9), special characters (@, ?, & etc.) and escape sequences like \n, \b etc. Whereas, the String literal represents objects of String class.

How is a string literal stored in the memory?

The characters of a literal string are stored in order at contiguous memory locations. An escape sequence (such as \\ or \") within a string literal counts as a single character. A null character (represented by the \0 escape sequence) is automatically appended to, and marks the end of, each string literal.


2 Answers

Is the second alternative safe and portable in this scenario?

Yes! The storage allocation of string literals is static and they persist for the lifetime of the application.

like image 170
Prasoon Saurav Avatar answered Oct 20 '22 09:10

Prasoon Saurav


Yes! But beware of this potential gotcha:

char * myFunc() {
    return "Constant string?";
}

Yes, you can convert a string literal to a non-const char *! This will enable you to later break the world by trying to modify the contents of that char *. This "feature" exists for legacy reasons -- string literals are older than const, and were originally defined as char * in C.

g++ throws out an obnoxious warning for this, even in the default mode, thankfully. I don't know if VC++ throws out a warning just as eagerly.

like image 43
Philip Potter Avatar answered Oct 20 '22 09:10

Philip Potter