tags:

views:

123

answers:

4

Can you do this?

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

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

A: 

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

jdv
+5  A: 

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.

Chris Becke
@Chris Becke: You meant 2.13.4/1. I can't edit it though!!
Chubsdad
thanks. fixed..
Chris Becke
A: 

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.

Nick Meyer
Except there's a specific rule in C++ that allows such an implicit conversion for backward compatibility with C code. I can't speak for C++0x though.
Mark B
And there is no reason why the compiler cannot place "String" in the .text section either.
doron
+1  A: 

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.

Johannes Schaub - litb