0
#include <iostream>
#include <cstring>

using namespace std;

const char * substringAfterLast(const char * str, const char * separator)
{
    if (str == NULL) {
        return NULL;
    } 
    else if (str[0] == '\0' || separator == NULL || separator[0] == '\0') {
        return "";
    }
    else {
        string ret(str);
        size_t found = ret.find_last_of(separator);
        ret = ret.substr(found + 1);
        cout << "before value = [" << const_cast<char*>(ret.c_str()) << "]" << endl;
        return const_cast<char*>(ret.c_str());
    }
}

int main(void)
{
    cout << "after value = [" << substringAfterLast("abc", "a") << "]" << endl;     
}

Result

before value = [bc]
after value = [**gabage value**]

Does the value disappear from memory at the end of the function? I do not understand why these values change.

YunjinJang
  • 165
  • 2
  • 7

1 Answers1

1

The pointer you get back from c_str() is strictly a const char* type. Futhermore, it is only valid up to the earlier of the lifetime of the backing string ret or when ret is modified in any way.

The behaviour of any code that does not adhere to these principles, such as yours, is undefined.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483