简体   繁体   English

如何判断const char *是否指向有效字符串?

[英]How can I tell if a const char* points to a valid string?

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? 在调试或发布模式下运行程序时,如何检查cstr仍指向字符串?

Would there be a way to determine this using exception handling in C++? 有没有办法使用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() . 调用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. 如果OTOH, clear()释放字符串的缓冲区,则cstr现在指向未分配的内存,但是即使如此,它仍取决于内存分配器如何处理它。 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. 调试分配器将用一些神奇的数字填充该块,例如0xDEADBEEF,生产分配器可能会使其保持不变,或者将整个页面返回给OS。

Whichever way you cut it, using the pointer returned by c_str() after the string has been mutated is undefined behaviour. 不管采用哪种方式剪切,在字符串被c_str()后使用c_str()返回的指针都是不确定的行为。 End of story. 故事结局。

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. 在更改了下标字符串之后, str.c_str()返回的指针不保证以任何方式有效。

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. 不是。

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. 以任何方式修改字符串后, c_str()的结果均无效。 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. 如果要继续使用文字(它在引号中专门指的是不可修改的字符串,此处为"string" ),请将其分配给单独的变量。

char const str_lit[] = "string";
std::string str = str_lit;
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM