Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ management of strings allocated by a literal

Tags:

c++

string

memory

Do I need to take care of memory allocation, scope and deletion of C++ strings allocated by a literal?

For example:

#include <string>

const char* func1() {
    const char* s = "this is a literal string";
    return s;
}

string func2() {
    std::string s = "this is a literal string";
    return s;
}

const char* func3() {
    std::string s = "this is a literal string";
    return s.c_str();
}

void func() {
    const char*  s1 = func1();
    std::string s2 = func2();
    const char*  s3 = func3();

    delete s1; //?
    delete s3; //?
}
  • func2: I don't need to delete s2.
  • func3: Do I need to delete s3?

Is func1 correct? Is character memory content still available after it leaving func1's scope? If yes, should I delete it when I do not need it anymore?

like image 226
rnd_nr_gen Avatar asked Oct 06 '10 13:10

rnd_nr_gen


1 Answers

  • func1() returns a pointer to a string literal. You must not delete string literals.
  • func2() (presumably, you omitted the std:: prefix) returns a std::string. It takes care of itself.
  • func3() returns a pointer to a string that's managed by a std::string object that's destroyed when the function exits. You must not touch that pointer after the function returns.
  • You would have to take care of the memory returned by this function:

    const char* func4() {
       char* s = new char[100];
       // fill char array with a string
       return s;
    }
    

However, manual resource management is tricky. For starters, if a function returns a naked pointer, you don't know whether it points to one objects (char) or an array thereof and whether you need to delete it. You should avoid all that and just stick to std::string.

like image 58
sbi Avatar answered Oct 13 '22 02:10

sbi