4 回答
If only from code perspective, this is safe. But you should make sure in test(), you can only assign a string const to str. If you do like following:
const char *test() {
char somestr[somesize];
str = somestr;
return str;
}
That's still not safe.
If you do the following, you can use the result of foo() anywhere. You should not modify or free it however. It is irrelevant if this code is part of a DLL or a Library.
const char * foo() {
return "hello";
}
// This is identical.
const char * foo() {
const char *x = "hello";
return x;
}
If you want to be able to modify, you could do something like this. Note that every call to foo()
will be referring to the same piece of memory because x
is static. Note that here, you can modify x
, but you still should not free it.
char * foo() {
static char x[] = "hello";
return x;
}
If you wanted to be able to free the result of foo()
, you must allocate the space with malloc()
.
The assignment to str
isn't even necessary. Even without it, it would be safe to return the address of a string literal from a function and to subsequently use the string anywhere.
It's safe if you assign a string literal to the pointer, but if you're going to do that it seems like it would be best to leave the function out of the picture entirely:
static char str[] = "hello world";
Then you could just use str
like a static char *
since arrays just decay to pointers.