1

guys, I need a little technical help. I'm working in C++, don't have much experience working in it but know the language somewhat. I need to use a C-style string (char array) but I need to allocate it on the heap.

If you look at this very simple piece of code:

#include <iostream>
using namespace std;

char* getText()
{
    return "Hello";
}

int main()
{
    char* text;
    text = getText();
    cout << text;
    //delete text; // Calling delete results in an error
}

Now, I'm assuming that the "Hello" string is allocated on the stack, within getText(), which means the pointer will be "floating" as soon as getText returns, am I right?

If I'm right, then what's the best way to put "Hello" on the heap so I can use that string outside of getText and call delete on the pointer if I need to?

Valdemar
  • 950
  • 1
  • 12
  • 20

4 Answers4

6

No, there's no hidden stack allocation going on there. "Hello" is static data, and ends up in the .data segment of your program.

This also means the string is shared for all calls to getText. A common use when this would be acceptable is if you have a large list of error messages that map to error codes. Functions like strerror work like this, so that you can get descriptive error messages for standard library error codes. But nobody is supposed to modify the return value of strerror (also because it is const). In your case, your function definition should read:

const char *getText()

If you do want a private copy of the string returned, you can use the strdup function to make a copy:

return strdup("Hello");
Stéphan Kochen
  • 19,513
  • 9
  • 61
  • 50
1

This is not right. "Hello" is a static string constant and it really should be const char*.

frast
  • 2,700
  • 1
  • 25
  • 34
1

Use a std::string, from the <string> header. Then use its .c_str() member function. Then you don't have to care about allocation and deallocation: it takes care of it for you, correctly.

Cheers & hth.,

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • agreed. this is the C++ way. you should not be thinking of C techniques in C++. – tenfour Nov 28 '10 at 19:08
  • Sounds like the best solution. I only need to be able to return a pointer to the string. Thanks everybody who replied :) – Valdemar Nov 28 '10 at 19:45
0

A narrow string literal has type "array of n const char", where n is the size of the string as defined below, and has static storage duration.

Static storage is neither automatic ("on the stack") nor dynamic ("on the heap"). It is allocated prior to the actual runtime of your program, so pointers to string literals never become invalid.

Note that char* p = "Hello" is deprecated because it is dangerous: the type system cannot prevent you from trying to change the string literal through p (which would result in undefined behavior). Use const char* p = "Hello" instead.

Community
  • 1
  • 1
fredoverflow
  • 256,549
  • 94
  • 388
  • 662