When you create local variables inside a function that are created on the stack, they most likely get overwritten in memory when exiting the function.
So code like this in most C++ implementations will not work:
char[] populateChar()
{
char* ch = "wonet return me";
return ch;
}
A fix is to create the variable that want to be populated outside the function or where you want to use it, and then pass it as a parameter and manipulate the function, example:
void populateChar(char* ch){
strcpy(ch, "fill me, Will. This will stay", size); // This will work as long as it won't overflow it.
}
int main(){
char ch[100]; // Reserve memory on the stack outside the function
populateChar(ch); // Populate the array
}
A C++11 solution using std::move(ch) to cast lvalues to rvalues:
void populateChar(char* && fillme){
fillme = new char[20];
strcpy(fillme, "this worked for me");
}
int main(){
char* ch;
populateChar(std::move(ch));
return 0;
}
Or this option in C++11:
char* populateChar(){
char* ch = "test char";
// Will change from lvalue to r value
return std::move(ch);
}
int main(){
char* ch = populateChar();
return 0;
}