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++?
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.