String :: c_str request

Where does the pointer return by calling the string: c_str ()? In the following code snippet, I thought I would give a segmentation error, but it gives me the correct result. If the pointer returned by the string :: c_str () points to an internal location inside the string object, then when the function returns and the destructor object starts, I must get invalid memory access.

#include <iostream> #include <string> using namespace std; const char* func() { string str("test"); return str.c_str(); } int main() { const char* p = func(); cout << p << endl; return 0; } Output: test Compiler: g++ 4.3.3 Platform: ubuntu 2.6.28-19 
+6
c ++ string
source share
2 answers

Where string::c_str() pointer return by calling string::c_str() on?

It points to the place in memory where the zero-terminated string is located, containing the contents of std::string .

The pointer is valid only until std::string is changed or destroyed. This is also potentially invalid if you call c_str() or data() again.

Basically, your safest bet is to assume that the pointer obtained from c_str() is invalid the next time you do something with the std::string object.

I must get invalid memory access.

No, you get undefined behavior. You may have received a memory access error (for example, a segmentation error), but your program may also work correctly. It may work once when you run your program, but do not execute the following.

+13
source share

What do you expect from printing?

 #include <iostream> #include <string> int main() { int* test = new int[20]; test[15] = 5; std::cout << test[15] << "\n"; delete[] test; std::cout << test[15] << "\n"; return 0; } 

In release mode on VS 2010, I get this result:

5
5

Unallocated memory does not necessarily throw an exception when trying to access it. The value does not have to be rewritten. (Interestingly, if I changed the compilation mode to debug mode, the compiler overwrites the value with -572662307 ).

What happens when you try to access it is undefined by standard. This means that the compiler can do anything, or do nothing. (Or crashing your program or blowing up the universe ...)

+2
source share

All Articles