简体   繁体   中英

Return char* to string literal

Can you do this?

char* func()
{
   char * c = "String";
   return c;
}

is "String" here a globally allocated data by compiler?

You can do that. But it would be even more correct to say:

const char* func(){
  return "String";
}

The c++ spec says that string literals are given static storage duration. I can't link to it because there are precious few versions of the c++ spec online. This page on const correctness is the best reference I can find.

Section 2.13.4 of ISO/IEC 14882 (Programming languages - C++) says:

  1. A string literal is a sequence of characters (as defined in 2.13.2) surrounded by double quotes, optionally beginning with the letter L, as in "..." or L"...". A string literal that does not begin with L is an ordinary string literal, also referred to as a narrow string literal. An ordinary string literal has type “array of n const char” and static storage duration (3.7), where n is the size of the string as defined below, and is initialized with the given characters. ...

  2. Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation defined. The effect of attempting to modify a string literal is undefined.

You can do this currently (there is no reason to, though). But you cannot do this anymore with C++0x. They removed the deprecated conversion of a string literal (which has the type const char[N] ) to a char * .

Note that this conversion is only for string literals. Thus the following two things are illegal, the first of which specifies an array and the second of which specifies a pointer for initialization

char *x = (0 ? "123" : "345"); // illegal: const char[N] -> char*
char *x = +"123"; // illegal: const char * -> char*

GCC incorrectly accepts both, Clang correctly rejects both.

The constant is not allocated on the heap but it is a constant. You don't need to destroy it.

Not in a modern compiler. In modern compilers, the type of "String" is const char * , which you can't assign to a char * due to the const mismatch.

If you made c a const char * (and changed the return type of the function), the code would be legal. Typically the string literal "String" would be placed in the executable's data section by the linker, and in many cases, in a special section for read-only data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM