Search code examples
testingmemory-leakscode-analysisstatic-analysis

Can static analysis detect memory leaks?


Having received my ISTQB certification a long time ago, I remember that it makes the following distinction:
-static analysis: performed on the source code, detects unreachable code, unassigned values etc.
-dynamic analysis: can detect memory leaks etc., requires execution (profiling).

But when I search today, I can see various sites and sources mentioning static analysis is capable of detecting memory leaks too.

So I wonder, is static analysis really capable of that? And if so, what is the different between dynamic analysis then, in terms of results?


Solution

  • A well designed/implemented static analysis tool can detect many cases where some code must have a leak, merely by analyzing the code. Tools like Coverity/Prevent do this pretty well.

    Such tools can also detect many cases where there might be a leak (and the Turing tarpit prevents it from knowing for sure). There is a huge argument about whether the tool should report these, because they might be false positives, and false positives are a waste of programmer time. [Worse: if a programmer wastes her time on several false positives, s/he often quits using the tool altogether, and now even the value of truly detected bugs are lost].

    Dynamic analysis tools can usually tell if a leak happens, at the moment it happens at runtime. (Imagine a pointer to heap being held in a local variable, and that local variable going out of scope). (See our CheckPointer tool for a dynamic analysis tool that can detect virtually every stack/heap allocation/pointer misuse error encountered at runtime).