How to make gcc warn about returning the address of local variables?

前端 未结 2 405
我寻月下人不归
我寻月下人不归 2020-12-17 17:50

With gcc 4.4.5, I have a warning with the following code.

char *f(void)
{
    char c;
    return &c;
}

But, when I use a t

2条回答
  •  情深已故
    2020-12-17 18:03

    In this first example, gcc can clearly see you're returning the address of an automatic variable that will no longer exist. In the second, the compiler would have to follow your program's logic, as p could easily point to something valid (e.g. an external character variable).

    Although gcc won't complain here, it will warn with pointer use like this:

    char *f(const char *x)
    {
      char *y = x;
      ...
    }
    

    Again, it can see without any doubt that you're removing the 'const' qualifier in this definition.

    Another utility that will detect this problem is splint (http://splint.org).

提交回复
热议问题