Is this a proper thing to do in C ?
char *func1() {
char *str[3] = { "so", "is", "amazing" };
return str[1];
}
The char *func1()
returns an pointer, pointing to a location in memory where the string is stored. But when the func1()
returns won't the str
array go out of scope and am I not returning a pointer to an object that does not exist? A dangling pointer (is this the right name?)
So I have two solutions make str
global so that it never goes out of scope and the pointer always pointer to a valid memory address, but that seems dirty.
The other solutions
char *func2() {
char *str[3] = { "so", "is", "amazing" };
int str1Len = strlen(str[1]);
char *ret = (char *)malloc(str1Len) ; // create a block of mem to hold the str[1].
strncpy(ret, str[1], str1Len);
return ret;
}
Is this correct ? What is the proper way to do this func1()
or func2()
?
Or is there a better way?
I have been using func1()
for some time and it has not created any problems for me, does this mean that func1()
is doing the right thing? and func2()
is unnecessary?