attractivechaos / klib

A standalone and lightweight C library

Home Page:http://attractivechaos.github.io/klib/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Ask for type less often

a-p-jo opened this issue · comments

For instance, the following :

#define kv_push(type, v, x) do {									\
		if ((v).n == (v).m) {										\
			(v).m = (v).m? (v).m<<1 : 2;							\
			(v).a = (type*)realloc((v).a, sizeof(type) * (v).m);	\
		}															\
		(v).a[(v).n++] = (x);										\
	} while (0)

can be rewritten as :

#define kv_push(v, x) do {									\
		if ((v).n == (v).m) {										\
			(v).m = (v).m? (v).m<<1 : 2;							\
			(v).a = realloc((v).a, sizeof(*(v).a) * (v).m);	\
		}															\
		(v).a[(v).n++] = (x);										\
	} while (0)

The key difference is that asking for type simply to take sizeof(type) can be error prone (and the errors can be hard to debug) and is redundant when the size of the type can be determined by taking sizeof() of a variable known to be of the same type in the structure passed to us. It is also sweeter syntax, as an aside.

Also, why do we use trust malloc()/realloc() to always succeed ?