Is returning a pointer to a static local variable safe?

First example: Somewhat safe

char* const GetString()
{
  static char sTest[5];
  strcpy(sTest, "Test");
  return sTest;
}

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* buffer and a maxsize for the GetString() 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

char* const GetString()
{
  return "Test";
}

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 GetString to take a parameter of a char* buffer to fill and a maxsize to 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.

Leave a Comment