Is returning a pointer to a static local variable safe?

前端 未结 7 1444
难免孤独
难免孤独 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:33

    It depends on what you mean by safe. There are a couple of problems that I can see immediately:

    1. You've returned a char * const, which will allow callers to change the string at this location. Potential buffer overrun. Or did you mean a const char *?
    2. You might have a problem with reentrance, or with concurrency.

    To explain the second, consider this:

    const char * const format_error_message(int err)
    {
        static char error_message[MAXLEN_ERROR_MESSAGE];
        sprintf(error_message, "Error %#x occurred", err);
        return error_message;
    }
    

    If you call it like this:

    int a = do_something();
    int b = do_something_else();
    
    if (a != 0 && b != 0)
    {
        fprintf(stderr,
            "do_something failed (%s) AND do_something_else failed (%s)\n",
            format_error_message(a), format_error_message(b));
    } 
    

    ...what's going to be printed?

    Same for threading.

提交回复
热议问题