I’ve recently come across an EE Times article written by Coverity stressing the benefits of static analysis and how it can help finding potential issues in the code early. They mentioned 3 static analysis techniques: Dataflow analysis This technique can find the defect in the listing below during compile time.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
void null_pointer_deref(int x) { char *p; if (x == 0) { p = foo(); } else { p = 0; } if(x != 0) { *p; } else { ... } } |
If value of x passed into the function is not zero, p is assigned a null pointer with p=0. Then, the next conditional check (x!=0) takes a true branch and in the next line p is dereferenced, leading to a null pointer dereference. This type of issue can be detected at compiled time with dataflow analysis. Interprocedural analysis This technique can find defects across function and method boundaries. See listing below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
void *zero_alloc(size_t size) { void *p = malloc(size); if (!p) return NULL; memset(p,0,size); return p; } struct S *create_S(int initial_value) { struct S *s = (struct S *) zero_alloc(sizeof(*s)); if (!s) return NULL; s->field = initial_value; return s; } int example_leak(struct S *s, int value) { struct S *tmp = s; if(!tmp) { tmp = create_S(value); } if(!tmp) return -1; ... return 0; } |
There are 3 functions: example_leak, create_S and zero_alloc. Interprocedural analysis can go through the code and identify the memory leak. The analysis engine has to trace the […]