'Use dataflow analysis to detect memory leak

I'm now learning static program analysis. After studying Dataflow analysis, I wonder if we can use dataflow analysis to detect any potential memory leaks?

To make it easy, suppose the instruction set are as below:

    1. p = alloc(); allocate a block of memory and assign its pointer to p.
    1. *p = v; write the scalar (non-pointer) value v to the location p. (Note that the value v is scalar, i.e. not a pointer.)
    1. v = *p; the read version of the above instruction (again, v couldn’t be a pointer).
    1. free(p); deallocate the block of memory pointed to by p.

We may treat each instruction as a basic block.There are 2 type of memory leak:

  1. forget free(p)
...
p = alloc()
...
  1. assign a value returned by alloc() to p which is not null
...

p = alloc();
...
p = alloc();
...

I think this analysis should be forward, so the general approach for dataflow analysis is to define a transfer function as formula

First, I think the Gen function should just be set the alloc instruction to 1, and the kill function is to work when the instruction is free(p) and set all instructions that assign an address to p to 0. But I think this cannot find the memory leak of type 2. Any help?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source