tags:

views:

31

answers:

1

What is the correct type to use for declaring a metavariable that possibly could match either variables or members in a struct?

Take for instance the following example source code:

#include <stdio.h>
#include <stdlib.h>

struct some_struct {
        int i;
        char *s;
};

void test(void)
{
        struct some_struct *ptr;
        char *s;

        s = malloc(100);
        ptr = malloc(sizeof(struct some_struct));
        ptr->s = malloc(100);

        puts("done");
}

With the following semantic patch:

@@
identifier ptr;
//idexpression ptr;
//expression ptr;
expression E;
@@

ptr = malloc(E);
+if (ptr == NULL)
+       return;

the ptr->s allocation is not matched unless expression ptr is used. To use expression for this seems a bit too broadly to me. Is this correct and the only way to do it?

+1  A: 

In general, you want to catch any lvalue pointer - but since you're only matching places where the expression is assigned a value from malloc, a plain expression will do the job fine (since a non-pointer or non-lvalue should make the compiler complain).

The problem you're going to have is if the expression has sideeffects, eg:

struct some_struct *a[10];
int i = 0;

a[i++] = malloc(sizeof(struct some_struct));
caf
Actually just "a[i]" is an expression as well, and I definitely want to support that. See also http://lists.diku.dk/pipermail/cocci/2010-January/000628.html
hlovdal