Assigning string :: c_str () to the char * constant when the string goes out of scope

I have doubts about using basic C ++. The code below, compiled using gcc / LInux, prints correctly.

The test string is out of scope, so its c_str() value must be invalid, right? Am I mistaken, or did I misunderstand the meaning of const char* ?

  #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 
+6
source share
5 answers

You are right, your code is invalid because it uses an object whose life has already expired. It works "by accident"; you cannot rely on it.

+12
source

This may be due to the row pool. However, this is an undefined behavior. We should not use the output of c_str () when a string goes out of scope.

+2
source

As long as the string object goes out of scope, the memory pointed to by a will still be there. I do not think that the standard says anything about clearing the actual memory locations when breaking a line.

+1
source

The program invokes undefined behavior. When a program does this, the compiler can do whatever it wants, including creating a program that works as you would expect.

The likely reason why he works the way he does is as follows. At the end of the inner block, test goes beyond and its destructor is launched. This frees up the block of memory used to store the actual string for other purposes, but the memory is not cleared (this will be a waste of time). Memory allocated in this way is not reused until bbbb one reason or another.

(Please note that the purpose and seal of cccc valid.)

+1
source

Since test is out of scope, you are executing undefined behavior. Do not make assumptions about how it will function.

This can be as good as segfault, and the behavior will still be correct. UB - UB.

0
source

Source: https://habr.com/ru/post/901425/


All Articles