I’m working with some code that widely uses the idiom of returning a pointer to a static local variable. eg:
char* const GetString() { static char sTest[5]; strcpy(sTest, 'Test'); return sTest; }
Am I right in thinking that this is safe?
PS, I know that this would be a better way of doing the same thing:
char* const GetString() { return 'Test'; }
Edit: Apologies, the function signature should of course be:
const char* GetString();
First example: Somewhat safe
Although not recommended, this is safe, the scope of a static variable remains alive even when the scope of the function ends. This function is not very thread-safe at all. A better function would get you to pass a
char* bufferand amaxsizefor theGetString()function to fill.In particular, this function is not considered a reentrant function because reentrant functions must not, amongst other things,
return the address to static (global) non-constant data. See reentrant functions.Second example: Completely unsafe
This would be safe if you did a
const char *. What you gave is not safe. The reason is because string literals can be stored in a read only memory segment and allowing them to be modified will cause undefined results.char* const(const pointer) means that you can’t change the address the pointer is pointing to.const char *(pointer to const) means that you can’t change the elements that this pointer is pointing to.Conclusion:
You should consider either:
1) If you have access to the code then modify the
GetStringto take a parameter of achar* bufferto fill and amaxsizeto use.2) If you do not have access to the code, but you must call it, wrap this method in another function which is protected by a mutex. The new method is as described in 1.