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 temporary pointer, there is no warning anymore (even if the behavior is wrong).
char *f(void)
{
char c;
char *p = &c;
return p;
}
I heard that pointer-analysis is difficult in C, but can gcc
warn about such code ?
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:
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).
Compilers, and most static analyzers, do not try to warn for everything wrong a program might do, because that would entail too many false positives (warnings that do not correspond to actual problems in the source code).
Macmade recommends Clang in the comments, a recommendation I can second. Note that Clang still aims at being useful for most developers by minimizing false positives. This means that it has false negatives, or, in other words, that it misses some real issues (when unsure that there is a problem, it may remains silent rather than risk wasting the developer's time with a false positive).
Note that it is even arguable whether there really is a problem in function
f()
in your program. Functionh()
below is clearly fine, although the calling code mustn't usep
after it returns:Another static analyzer I can recommend is Frama-C's value analysis (I am one of the developers). This one does not leave any false negatives, for some families of errors (including dangling pointers), when used in controlled conditions.
The above are only informative messages, they do not mean the function is necessarily wrong. There is one for my function
h()
too:The real error, characterized by the word “assert” in Frama-C's output, is if a function calls
h()
and then usesp
:Frama-C's value analysis is called context-sensitive. It analyses function
h()
for each call, with the values that are actually passed to it. It also analyzes the code that comes after the call toh()
in functioncaller()
with the values that can actually be returned byh()
. This is more expensive than the context-insensitive analyses that Clang or GCC typically do, but more precise.