C++ string: Invalid pointer error

前端 未结 3 759
别跟我提以往
别跟我提以往 2021-01-28 05:43

I am getting an invalid pointer error when I call the below function. Why is this happening?

void Get(const char* value)
{
    string st(\"testing string\");
            


        
相关标签:
3条回答
  • 2021-01-28 06:02

    val variable inside Get() gets destroyed once Get() returns, thus the pointer to val body becomes invalid. Also value parameter is a copy of the original pointer, so the original val pointer in main() function is left unchanged and still holds a null pointer value.

    Change it to

    string Get()
    {
        string st("testing string");
        string val = st.substr(1, st.length()); 
        return val;
    }
    
    0 讨论(0)
  • 2021-01-28 06:07

    I see two mistakes:

    • You assign a val.c_str() to a pointer that is local to GetVal();
    • val is destroyed at the end of GetVal(), so the pointer value would be invalid anyway.
    0 讨论(0)
  • 2021-01-28 06:07

    Prefer using std::string.

    string Get()
    {
        string st("testing string");
        return st.substr(0, st.length()/2);//returning substring
    }
    
    string s = Get();
    

    By the way, an interesting article (by Herb Sutter) you would like to read now is:

    GotW #88: A Candidate For the “Most Important const”

    0 讨论(0)
提交回复
热议问题