简体   繁体   English

string :: c_str查询

[英]string::c_str query

Where does the pointer returned by calling string::c_str() point to ? 通过调用string :: c_str()返回的指针指向何处? In the following code snippet, I thought I will give get a segmentation fault but it gives me the correct output. 在下面的代码片段中,我以为我会遇到分段错误,但它会为我提供正确的输出。 If the pointer returned by string::c_str() points to an internal location inside the string object, then when the function returns and the object destructor gets invoked, I should get an invalid memory access. 如果string :: c_str()返回的指针指向字符串对象内部的内部位置,那么当函数返回并且调用对象析构函数时,我应该获得无效的内存访问。

#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

Where does the pointer returned by calling string::c_str() point to? 通过调用string::c_str()返回的指针指向何处?

It points to some place in memory where a null-terminated string containing the contents of the std::string is located. 它指向内存中某个包含std::string内容的以空终止的字符串的位置。

The pointer is only valid until the std::string is modified or destroyed. 该指针仅在std::string被修改或销毁之前才有效。 It is also potentially invalidated if you call c_str() or data() again. 如果再次调用c_str()data() ,它也可能无效。

Basically, your safest bet is to assume the pointer obtained from c_str() is invalidated the next time you do something to the std::string object. 基本上,最安全的选择是假设下次您对std::string对象执行操作时,从c_str()获得的指针无效。

I should get an invalid memory access. 我应该获得无效的内存访问权限。

No, you get undefined behavior. 不,您会得到不确定的行为。 You might get a memory access error of some kind (like a segmentation fault), but your program also might appear to continue running correctly. 您可能会遇到某种内存访问错误(例如分段错误),但是您的程序似乎也可以继续正常运行。 It might appear to work one time you run your program but fail the next. 它可能在您一次运行程序时起作用,但下次却失败。

What would you expect this to print out? 您希望将其打印出来吗?

#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: 在VS 2010的发布模式下,我得到以下结果:

5 5
5 5

Deallocated memory doesn't necessarily throw an exception when you try to access it. 当您尝试访问已释放的内存时,不一定会引发异常。 The value doesn't necessarily get re-written, either. 该值也不一定要重写。 (Interestingly enough, if I change the compile to debug mode, the compiler overwrites the value with -572662307 ). (有趣的是,如果我将编译方式更改为调试方式,则编译器将使用-572662307覆盖该值)。

What happens when you try to access it is undefined by the standard. 标准未定义您尝试访问它时会发生什么。 That means the compiler can do whatever it feels like doing, or choose to do nothing. 这意味着编译器可以做任何想做的事情,或者选择什么都不做。 (Or crash your program, or blow up the universe...) (或者崩溃程序,或者炸毁宇宙……)

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

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