[Cocci] Question to stackoverflow answer for finding malloc assignment not followed by if NULL test‎

Julia Lawall julia at diku.dk
Tue Nov 17 18:38:21 CET 2009

On Tue, 17 Nov 2009, Håkon Løvdal wrote:

> Julia has already answered my question about how to add missing
> NULL tests after malloc
> (http://stackoverflow.com/questions/1716086/adding-missing-null-checks-after-malloc-with-coccinelle).
> However, the semantic patch fails to correct variables that
> are initialized with a call to malloc in the variable declaration statement.
> E.g. for
>         static void test1(void)
>         {
>                 char *ptr = malloc(100);
>                 strcpy(ptr, "abcd");
>         }
>         static void test2(void)
>         {
>                 char *ptr;
>                 ptr = malloc(100);
>                 strcpy(ptr, "abcd");
>         }
> only test2 is corrected. Is this because of 1) lack of support
> in Julia's answer or 2) a bug?

It is an intentional omission.  You would have to make a special case for 
this.  The problem is that you want to put the test as the next statement, 
and if you just match an expression, eg ptr = malloc(...), with no 
semicolon at the end, Coccinelle doesn't know where the next statement 
is.  Furthermore, in C, or at least in Linux kernel code, you 
can't/shouldn't mix statements and declarations.  So if the malloc is in a 
declaration, you have to skip to just before the first real statement in 
the function.

You could try the following:

type T;
identifier x;
statement S1, S2;

T x = malloc(...);
... when != S1
++ if(!x) return;

(You would have to adapt it to your more careful case, where you don't 
want to introduce testing if it is there already)

In this semantic patch, the when != S1 is there to skip over all of the 
remaning declarations.  S2 is there to match the first non-declaration 

A recent addition to Coccinelle is the use of ++.  This allows multiple 
instances of the error checking code to be added to a single code point.  
This addresses the issue that there might be more than one malloc call 
within the declarations.


More information about the Cocci mailing list