Tay Ray Chuan home archive

pre-emptive memory allocation

Mon, 11 Jul 2011 02:03:43 +0800 | Filed under gsoc 2011 git diff

While scanning xprepare.c:xdl_prepare_ctx() [1] in the hopes of speed-ups, I stumbled over this gem.

What puzzled me was this expression in xdl_cha_alloc():

chanode_t *ancur;
ancur = (chanode_t *) xdl_malloc(sizeof(chanode_t) + cha->nsize);

Huh? Passing sizeof(chanode_t) made sense, but adding cha->nsize?Where does nsize come from? Turning to xdl_cha_init():

int xdl_cha_init(chastore_t *cha, long isize, long icount) {
	/* ... */
	cha->nsize = icount * isize;
	/* ... */

We know that xdl_cha_init() is called like this:

xdl_cha_init(&cha, sizeof(struct foo), n);

Now I was getting close. Back to xdl_cha_alloc():

chanode_t *ancur;
void *data;
/* ... */
ancur = (chanode_t *) xdl_malloc(sizeof(chanode_t) + cha->nsize);
/* ... */
data = (char *) ancur + sizeof(chanode_t) + ancur->icurr;
ancur->icurr += cha->isize;

return data;

Aha! So what it does is it "advances a read head", like you do with fseek()/ftell(), and returns you a chunk of memory. Marvelous.

[1] Code extracts were from LibXDiff (LGPL); to be specific, from git's 'fork' of LibXDiff, but the code is almost entirely unmodified since being integrated into git's own codebase.

blog comments powered by Disqus