0

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.

Andy Cong
  • 109
  • 1
  • 10
  • UB is UB, seems to works is possible output. – Jarod42 May 04 '20 at 06:52
  • 4
    There is no way to determine that a pointer is valid, including using it to see what happens. As the old saying goes, undefined behaviour is undefined. – molbdnilo May 04 '20 at 06:53
  • 1
    Being able to print the content of a pointer does not prove that the pointer is valid. – john May 04 '20 at 07:01

3 Answers3

3

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
2

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

Benquan Yu
  • 51
  • 3
  • "but luckily" *seeming to work* is the *worst* symptom of undefined behaviour. Failing loudly is much more preferable – Caleth May 04 '20 at 08:32
1

Just guessing, but:

Ondřej Navrátil
  • 453
  • 1
  • 4
  • 11
  • 1
    C++ is not managed like C#, so its not a matter of the operating system. The pointer just points to a location that was not modified in the meantime so it happens to print the correct string. If you did something between the scope and the 2nd print, you probably see garbage... – Lior May 04 '20 at 07:22