arena icon indicating copy to clipboard operation
arena copied to clipboard

Segmentation fault when optimized

Open alsakandari opened this issue 1 year ago • 1 comments

I had some issues lately when I optimize the code with gcc -O2 or any level above 0, It gives me segfault at arena_da_append because of accessing the memory got from arena_alloc, the weird thing is that it first made it through 4 or more allocations

alsakandari avatar May 17 '24 06:05 alsakandari

@yhyadev It's hard to tell exactly what's happening, but based off of what you're describing it sounds like a memory alignment issue. I've experienced something similar when allocating large numbers of strings to a similar type of arena allocator.

Something you can try is getting the alignment of your type with _Alignof() and doing something like the following:

void * foo_alloc(Arena *arena, size_t size, size_t alignment -- *your alignment you got with _Alignof()*)
{
    size = (size + alignment - 1) & ~(alignment - 1);

    ...
       allocation related code
    ...

    uintptr_t current = (uintptr_t)arena->region->data + arena->region->size;
    uintptr_t aligned = (current + alignment - 1) & ~(alignment - 1);

    arena->region->size = aligned - (uintptr_t)arena->region->data + size;

    return (void *)aligned;
}

I'm working from memory here, so you may have to tweak some things, but it could be worth a shot to see if that's your issue.

Sorry if this doesn't help.

drewjohnson2 avatar Oct 28 '24 20:10 drewjohnson2

Sorry if this doesn't help.

I stopped already working with C, and removed arena.h from the project as I didn't need it, It would be better for someone else that got a similar issue to try this solution

alsakandari avatar Oct 29 '24 02:10 alsakandari

https://github.com/tsoding/arena/issues/3#issuecomment-2442563626

I was wondering if aligment would be an issue. Its totally solvble with a bit of elbow grease and some macro work. alternativly just make sure to use 1 and only 1 size per arena. this is equivelent to malloc(x*sizeof(Type)) in terms of aligment.

nevakrien avatar Feb 25 '25 19:02 nevakrien