简体   繁体   中英

assigning string::c_str() to a const char* when the string goes out of scope

I have a doubt on basic C++ usage. The code below, compiled with gcc/LInux, prints out correctly.

The string test goes out of scope so also its c_str() value should be invalid isn't it? Am I wrong or do I have misunderstood the const char* meaning?

   #include <iostream>
   int main(){
     const char* a = "aaaa";
       std::cout << a;
       { std::string test("bbbb");a=test.c_str();}
       std::cout << a;
       a = "cccc";
       std::cout << a;
   }


   aaaabbbbcccc
   // print out without any problem

You're right, your code is not valid since it uses an object whose lifetime has already ended. It works "by accident", you cannot rely on that.

It could be because of string pooling. Neverthless, it is Undefined behavior. We should not use the c_str() output once the string goes out of scope.

While the string object goes out of scope, the memory pointed to by a will still be there. I don't think the standard says anything about clearing the actual memory locations when a string is destructed.

The program invokes undefined behavior. When a program does that, the compiler is free to do whatever it wishes, including creating a program that works as one might expect.

The likely reason why it works the way it does is as follows. At the end of the inner block, test goes out of scope and its destructor is run. This frees the block of memory used to hold the actual string for other uses, but the memory is not cleared (that would be a waste of time). The memory thus freed is not, for one reason or another, reused before bbbb is printed out.

(Note that the cccc assignment and printout is valid.)

Because test goes out of scope, what you are doing is undefined behavior. Do not make assumptions about how it will function.

It could just as well segfault and the behavior will still be correct. UB is UB.

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