char * concat(const char *s1, const char *s2) {
char result[70];
strcpy(result, s1);
strcat(result, s2);
return result;
}
int main() {
char *s1 = "Hello";
char *s2 = " World!";
char *s3 = concat(s1, s2);
printf("%s\n", s3);
return 0;
}
This program just calls the concat
function which returns a char *
that is the concat of s1 and s2
. However, upon compiling, I get the error address of stack memory associated with local variable 'result' returned
.
So I understand that result
is a local variable in the concat function, but not really why we have to malloc it. Why doesn't result just get returned with Hello World
as it's value?
If you consider a program like this:
int ret() {
int a = 4;
return a;
}
int main() {
int b = ret();
printf("%d\n", b); // 4
return 0;
}
there is no error. I don't have to malloc the int. a
is local, but I still return it and it still works.
I want to know what's the main difference between concat and ret, and why concat must dynamically allocate memory. Thank you.