[XviD-devel] mem_align.c bug

suxen_drol xvid-devel@xvid.org
Fri, 13 Dec 2002 00:12:10 +1100


On Thu, 12 Dec 2002 10:13:17 +0000 pikatu <pikatu@012.net.il> wrote:

> 
> You still have a bug there since in the case of no alignment the free routine 
> will fail.

for those who want to know:

the memory ptr passed to xvid_free() does NOT point to the address of
the the "allocated block", instead, it points to an
"aligned address" WITHIN the allocated block.

to free the allocated block, we must first calculate the "allocated
address" from the "aligned address". to do this, xvid stores an "offset"
located one-byte before the "aligned address": eg.

void xvid_free(void * mem_ptr)
{
	uint8_t * p = (uint8_t*) mem_ptr;
	p -= p[-1];
	free(p);
}

currently, when xvid_malloc() is called with alignment=0, the offset
value is set to zero. e.g:

void * xvid_alloc(int num_bytes, int alignment)
{
	if (alignment == 0)
	{
		uint8_t * mem_ptr = malloc(num_bytes + alignment + 1);
		*mem_ptr = 0;
		return mem_ptr++;
	}else{
		/* ... */
	}
}

however when we call xvid_free() the value of  p[-1] is zero, causing
free() to be called on the "aligned address" and not the "allocated
address".

the solution to this problem, use:  *mem_ptr = 1;

ed: assuming my above rant is correct, i will let you commit this fix.

> By the way, why not set the default alignment to something more
> reasonable 
> than 1 ? 

one?? 
alignment is specified in #define CACHE_LINE, xvidcore/src/portab.h

-- pete; life is like a box of ammo