Andy Cong
Andy Cong

Reputation: 109

The lifetime of pointer that point to c_str function in std::string

Firstly the code listed as follow.

#include<string>
#include<stdio.h>

int main(){

    const char *cs;
    {
        std::string s("123456");
        cs = s.c_str();
        printf("cs = %s\n",cs);
    }
    printf("cs = %s\n",cs);
    return 0;
}

run it, and result as follow. (Linux gcc )

cs = 123456
cs = 123456

So, I don't know why the cs pointer is valid after the s is destroyed. in other words, the lifetime of pointer that point to c_str function in std::string.

Upvotes: 0

Views: 303

Answers (3)

Benquan Yu
Benquan Yu

Reputation: 51

This is a typical use-after-free problem, the piece of memory cs points to is freed, but luckily, it have not yet been returned to kernel or reused by your program. The behavior of use-after-free is undefined, and you should not do so. It is one of the most difficult problem to deal with. Google open sourced a tool to help you to detect use-after-free in your code: https://github.com/google/sanitizers/wiki/AddressSanitizer

Upvotes: 2

Remy Lebeau
Remy Lebeau

Reputation: 598134

The code has undefined behavior.

In the second printf(), the cs pointer is still pointing at memory that has been freed. The fact that you get the same output simply means the content of that memory has not been overwritten yet. But it is still invalid to access freed memory.

Upvotes: 3

Ondřej Navr&#225;til
Ondřej Navr&#225;til

Reputation: 601

Just guessing, but:

Upvotes: 1

Related Questions