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?
char * str[3] = { "so" , "is" ,"amazing" } ;is declared within the function and ceases to exists when the function returns. (it is local to the function, and that memory is released when the function returns -- so the memory pointed to bystr[1]no longer exists) You must either passstrto the function as a parameter, or allocate storage forstrwithmallocwithin the function and return a pointer to the new block of memory.strarray itself has automatic storage, but its elements being pointers to string literals, that have static storage. It's OK to return one of them, pointers are returned by value.strdoes not change, make itstatic const char * const str[] = .... That qualifies both, the array and thechar []it points toconst. Thestaticmakes it permanent and the rest makes it startup-time initialised. Your current version will setup the array for every call.