Skip to content

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

@GoogleCodeExporter

Description

@GoogleCodeExporter
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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions