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