string::c_str query

后端 未结 2 1116
星月不相逢
星月不相逢 2021-01-18 04:15

Where does the pointer returned by calling string::c_str() point to ? In the following code snippet, I thought I will give get a segmentation fault but it gives me the corre

2条回答
  •  花落未央
    2021-01-18 04:57

    What would you expect this to print out?

    #include 
    #include 
    
    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

    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).

    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...)

提交回复
热议问题