cii icon indicating copy to clipboard operation
cii copied to clipboard

memchk.c - sometimes malloc doesn't return aligned pointer

Open GoogleCodeExporter opened this issue 10 years ago • 1 comments

I'm trying to use the memchk.c library to check some of my code, but I was 
getting an assertion error on FREE'ing because this test was failing:

    ((unsigned long)ptr) % (sizeof (union align)) != 0

Upon review, it looks like it is a result of malloc not returning a pointer 
that is aligned according to `sizeof(union align)`.  For example, I added the 
following check to the `dalloc` function:


    size_t alignment = sizeof(union align);
    assert((alignment & (alignment - 1)) == 0); // make sure alignment is a power of 2
    void *nptr = (void *)(((unsigned long)ptr + (alignment-1)) & ~ (size_t)(alignment-1));
    assert(ptr == nptr);

And my code would fail, but I would expect that nptr should equal ptr?  If the 
code was modified to change:

    avail->ptr  = ptr;

to:
    avail->ptr  = (void *)(((unsigned long)ptr + (alignment-1)) & ~ (size_t)(alignment-1));

I don't think it would have any affect other than to assure that the memory is 
aligned along the boundaries we believe it is.

Original issue reported on code.google.com by [email protected] on 26 Jul 2011 at 4:22

GoogleCodeExporter avatar Mar 23 '15 17:03 GoogleCodeExporter

Sorry, also realized you must change avail->size:

    avail->size = size - ((ptr == nptr) ? 0 : alignment);

Original comment by [email protected] on 26 Jul 2011 at 5:32

GoogleCodeExporter avatar Mar 23 '15 17:03 GoogleCodeExporter