0

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");
    string val = st.substr(1, st.length()); 
    value = val.c_str();        
}

int main()
{
    const char *val = NULL;
    GetVal(val);
    cout<<val;
}

The objective is to return the substring.

3 Answers 3

8

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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”

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.