Is returning a pointer to a static local variable safe?

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

    It is very useful, as you can use the function directly as printf parameter. But, as it was mentioned, multiple calls to the function inside a single call will cause a problem, because the function uses the same storage and calling it twice will overwrite the returned string. But I tested this piece of code and it seems to work - you can safety call a function, where givemestring is used at most MAX_CALLS times and it will behave correctly.

    #define MAX_CALLS 3
    #define MAX_LEN 30
    
    char *givemestring(int num)
    {
            static char buf[MAX_CALLS][MAX_LEN];
            static int rotate=0;
    
            rotate++;
            rotate%=sizeof(buf)/sizeof(buf[0]);
    
            sprintf(buf[rotate],"%d",num);
            return buf[rotate];
    
    }
    

    The only issue is thread-safety, but this can be solved with thread local variables (gcc's __thread keyword)

提交回复
热议问题