Hi, I've written a semantic patch to check for wrong size allocation.
Using python was the only way I found out to check if type T1 is
different from T2. Following the semantic patch:

-----------------------------------------------------------
@bug exists@
type T1, T2;
T1 *a;
T2 *b;
expression E;
position p;
identifier c;
@@
(
a...@p = calloc(sizeof(*b), E);
|
a...@p = calloc(sizeof(T2), E);
|
T1 *...@p = calloc(sizeof(*b), E);
|
T1 *...@p = calloc(sizeof(T2), E);
)

@script:python depends on bug@
p << bug.p;
t1 << bug.T1;
t2 << bug.T2;
@@

if t1 != t2:
    print "WARNING: wrong size to calloc function => %s:%s" %
(p[0].file, p[0].line)
    print "         Type is '%s', but 'sizeof(%s)' was allocated" % (t1, t2)

-----------------------------------------------------------


I've used the code attached to test the correctness of the results.
Any comments ? I think I can add more checks for when there are casts.

This is a common error when someone else renamed the variable or the
type without properly updating the allocation lines. This happened
today in one of the projects I work on.


Lucas De Marchi
#include <stdio.h>
#include <stdlib.h>

struct a {
	int b;
	int c;
};

struct b {
	int a;
	int b;
	int c;
};


int main(int argc, char *argv[])
{
	struct b *b = calloc(sizeof(*b), 1);
	struct a *a = calloc(sizeof(*b), 1);
	free(a);
	free(b);

	a = calloc(sizeof(*b), 1);
	free(a);

	a = calloc(sizeof(*a), 1);
	free(a);

	a = calloc(sizeof(struct b), 1);
	free(a);

	a = calloc(sizeof(struct a), 1);
	free(a);

	return 0;
}
_______________________________________________
Cocci mailing list
[email protected]
http://lists.diku.dk/mailman/listinfo/cocci
(Web access from inside DIKUs LAN only)

Reply via email to