vm overcommit handling

Werner Almesberger werner at openmoko.org
Fri Jan 21 10:16:25 EST 2011

Sebastien Bourdeauducq wrote:
> Don't most applications do that, regardless of the overcommit_memory
> setting? In C programs, checking malloc() return value for NULL is so
> messy... :)

I like malloc to fail right there and then, instead of having a NULL
pointer that gets passed around until it eventually is dereferenced
who knows where.

To avoid tedious error checks, I have these macros:

#define alloc_size(s)					\
    ({  void *alloc_size_tmp = malloc(s);		\
	if (!alloc_size_tmp)				\
		abort();				\
	alloc_size_tmp; })

#define alloc_type(t) ((t *) alloc_size(sizeof(t)))

alloc_type makes malloc type-safe, removing common problems like

	ptr = malloc(sizeof(ptr));	// should be sizeof(*ptr)


	struct something *foo;
	foo = malloc(sizeof(struct foo));

which later gets changed to

	struct something_else *foo;
	foo = malloc(sizeof(struct foo));

And there's also

#define stralloc(s)					\
    ({  char *stralloc_tmp = strdup(s);			\
	if (!stralloc_tmp)				\
		abort();				\
	stralloc_tmp; })

- Werner

More information about the discussion mailing list