5
char* stringReturn()
{
char a[] = "Array of characters";
//return a; // I know stack allocation should not be returned

char *b = "Pointer to a string";
return b; // Is it safe ? 
} 


int main() {    
    char *str = stringReturn ();
    cout<< str; 
    return 0; }

This is safe means then where the data "Pointer to a string" will be stored in the memory.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
SridharKritha
  • 8,481
  • 2
  • 52
  • 43
  • 1
    Possible duplicate of [http://stackoverflow.com/questions/2327841/c-string-literal-data-type-storage](http://stackoverflow.com/questions/2327841/c-string-literal-data-type-storage) – jrok Apr 02 '12 at 17:39
  • See also: http://stackoverflow.com/questions/349025/is-a-string-literal-in-c-created-in-static-memory – Robᵩ Apr 02 '12 at 17:39
  • 5
    Note that, actually, you are writing C code, never mind `std::cout`. This has disadvantages. One of those is that string handling is rather complicated and dangerous. (For starters `b` should be a `const char*`; callers trying to modify it will blow up the earth. Returning `a` would be a disaster, too, and returning a dynamically allocated array of chars a maintenance nightmare.) Have you considered using `std::string`? Do so, and those problems simply vanish. – sbi Apr 02 '12 at 17:46

2 Answers2

11

Yes, it is safe to return the value of b. The string literal to which b points has static storage duration.

But, you must declare your pointers const-correctly. b must be const char*b.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
6

There is a difference between the char[] and char* variable declarations. As you noted in the comment in the code, char a[] allocates the memory for a on the stack and copyies the characters to that array, essentially making the declaration the same as:

char a[] = {'A', 'r', 'r', 'a', 'y', ' ', 'o', 'f', ..., '\0'};

When the function exits, the memory allocated on the stack for the array is gone, no longer making it safe to refer to via pointers.

When delcaring the variable via char* b, the address of a statically allocated char array is stored in the memory for pointer b. The actual memory where the string is allocated is not specified by the standard, but will be accessible throughout the execution of the code (in fact the compiler might reuse that memory if you declare another variable of char* with the exact same string) -- so it is safe to pass that address around (e.g as a return value from a function).

As Rob pointed out, you should declare the type of the pointer const char* to avoid accidentally trying to write to the memory where the string is stored: it is not guaranteed by the standard to have been placed in a writable segment of the memory. If you need to change it, you need to dynamically allocate the memory, copy the string into that allocated memory and return/work with that.

Attila
  • 28,265
  • 3
  • 46
  • 55