C++ management of strings allocated by a literal

后端 未结 4 1519
终归单人心
终归单人心 2020-12-10 15:44

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

For example:

<         


        
4条回答
  •  忘掉有多难
    2020-12-10 16:27

    I snip the relevant code to each function and treatment of its return value, and comment below:

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

    You can't delete s1, as the string it points to does not live on the heap.

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

    This is fine. func2's s goes out of scope and cleans up. s2 will duplicate the string from s, and also clean itself up at the end of func.

    const char* func3() {
       string s = "this is a literal string";
       return s.c_str();
    }
    const char*  s3 = func3();
    delete s3; //?
    

    func3 returns a pointer to a string that has been freed. You will get a double free exception upon execution of delete s3.

提交回复
热议问题