简体   繁体   中英

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.

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.

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

Just guessing, but:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM