2
4

4 回答 4

1

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.

于 2012-12-25T03:11:36.247 回答
1

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().

于 2012-12-25T03:18:26.613 回答
0

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.

于 2012-12-25T03:12:58.440 回答
0

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.

于 2012-12-25T03:18:47.937 回答