Alex Rivera | Logout

Is returning a pointer to a static local variable safe?

Asked 2009-01-17T17:51:59.557
58

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();
Edit
Report

2 Answers

43

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.

answered 2009-01-17T18:10:41.250
0

Yes, this is used frequently to return the text portion of some lookup, i.e. to translate some error number into a human friendly string.

Its wise to do this in instances where you'd:

fprintf(stderr, "Error was %s\n", my_string_to_error(error_code));

If my_string_to_error() returned an allocated string, your program would leak given the above (very) common usage of such a function.

char const *foo_error(...)
{
    return "Mary Poppins";
}

... is also OK, some brain dead compilers might want you to cast it though.

Just watch strings in this fashion, don't return a book :)

answered 2009-01-17T18:05:38.717

Your Answer