Is returning a pointer to a static local variable safe?

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

    Yes, it's perfectly safe. The lifetime of local statics are that of the entire program execution in C. So you can return a pointer to it, since the array will be alive even after the function returns, and the pointer returned can validly de-referenced.

    0 讨论(0)
提交回复
热议问题