C/C++ Char Pointer Crash

前端 未结 7 469
甜味超标
甜味超标 2020-12-19 17:42

Let\'s say that a function which returns a fixed ‘random text’ string is written like

char *Function1()
{ 
return “Some text”;
}

then the p

7条回答
  •  一整个雨季
    2020-12-19 18:23

    You are trying to modify a string literal. According to the Standard, this evokes undefined behavior. Another thing to keep in mind (related) is that string literals are always of type const char*. There is a special dispensation to convert a pointer to a string literal to char*, taking away the const qualifier, but the underlying string is still const. So by doing what you are doing, you are trying to modify a const. This also evokes undefined behavior, and is akin to trying to do this:

    const char* val = "hello";
    char* modifyable_val = const_cast(val);
    modifyable_val[1] = 'n';  // this evokes UB
    

    Instead of returning a const char* from your function, return a string by value. This will construct a new string based on the string literal, and the calling code can do whatever it wants:

    #include 
    
    std::string Function1()
    { 
    return “Some text”;
    }
    

    ...later:

    std::string s = Function1();
    s[1] = 'a';
    

    Now, if you are trying to change the value that Function() reuturns, then you'll have to do something else. I'd use a class:

    #include 
    class MyGizmo
    {
    public: 
      std::string str_;
      MyGizmo() : str_("Some text") {};
    };
    
    int main()
    {
      MyGizmo gizmo;
      gizmo.str_[1] = 'n';
    }
    

提交回复
热议问题