views:

64

answers:

3
std::string str = "string":
const char* cstr = str.c_str();
str.clear();
//here, check if cstr points to a string literal.

How do i check if cstr still points to a string when running the program in debug or release mode?

Would there be a way to determine this using exception handling in C++?

+6  A: 

There is no portable way to do this. The implementation is perfectly free to hold onto the buffer, unmodified, after the call to clear(). If, OTOH, clear() frees the string's buffer, cstr is now pointing into unallocated memory, but even then it depends on how the memory allocator handles it. A debug allocator will fill the block with some magic number like 0xDEADBEEF, and a production allocator might leave it untouched, or give the entire page back to the OS.

Whichever way you cut it, using the pointer returned by c_str() after the string has been mutated is undefined behaviour. End of story.

Marcelo Cantos
+1  A: 

There is no need to check anything. By definition, it doesn't. The result of c_str() is invalid once the string is modified in any way. Perhaps using it once doesn't crash, but the next time might. Crashes are rarely guaranteed.

If you want to continue working with the literal (which specifically refers to a non-modifiable string in quotes, "string" here), assign it to a separate variable.

char const str_lit[] = "string";
std::string str = str_lit;
...
Potatoswatter
+2  A: 

You can't.

The pointer returned by str.c_str() in not guaranteed to be valid in any way after the underling string has been changed.

For example, you might find a string there, or find a null there, or throw an access violation error.

I suspect that you've got code that doesn't understand this, and you're trying to test whether access that pointer is safe. It isn't.

egrunin