Fundamentally, yes, it is safe in the sense that the value will last indefinitely because it is static.
It is not safe in the sense that you've returned a constant pointer to variable data, rather than a variable pointer to constant data. It is better if the calling functions are not allowed to modify the data:
const char *GetString(void)
{
static char sTest[5];
strncpy(sTest, "Test", sizeof(sTest)-1);
sTest[sizeof(sTest)-1] = '\0';
return sTest;
}
In the simple case shown, it is hardly necessary to worry about buffer overflows, though my version of the code does worry, and ensures null termination. An alternative would be to use the TR24731 function strcpy_s
instead:
const char *GetString(void)
{
static char sTest[5];
strcpy_s(sTest, sizeof(sTest), "Test");
return sTest;
}
More importantly, both variants return a (variable) pointer to constant data, so the user should not go modifying the string and (probably) trampling outside the range of the array. (As @strager points out in the comments, returning a const char *
is not a guarantee that the user won't try to modify the returned data. However, they have to cast the returned pointer so it is non-const and then modify the data; this invokes undefined behaviour and anything is possible at that point.)
One advantage of the literal return is that the no-write promise can usually be enforced by the compiler and operating system. The string will be placed in the text (code) segment of the program, and the operating system will generate a fault (segmentation violation on Unix) if the user attempts to modify the data that is pointed to by the return value.
[At least one of the other answers notes that the code is not re-entrant; that is correct. The version returning the literal is re-entrant. If re-entrancy is important, the interface needs to be fixed so that the caller provides the space where the data is stored.]