Ie., why does the following work:
char* char_array(size_t size){
return new char[size];
}
int main(){
const char* foo = "foo";
size_t len = strlen(foo);
char* bar=char_array(len);
memset(bar, 0, len+1);
}
But the following segfaults:
void char_array(char* out, size_t size){
out= new char[size];
}
int main(){
const char* foo = "foo";
size_t len = strlen(foo);
char* bar;
char_array(bar, len);
memset(bar, 0, len+1);
}
Passing ‘bar’ to char_array is passing a copy of the present value of that pointer at the time of the call – so ‘out’ in char_array points to the same thing as ‘bar’ but they’re completely isolated variables, and when char_array returns the newly allocated value is simply lost.
If you want to actually modify the ‘bar’ variable, you need to pass a pointer or reference to the bar variable itself, i.e.
or