Is returning a pointer to a static local variable safe?

前端 未结 7 1375
难免孤独
难免孤独 2020-11-27 04:21

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[         


        
7条回答
  •  一整个雨季
    2020-11-27 04:42

    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 :)

提交回复
热议问题