dev1223
dev1223

Reputation: 1159

Strange behavior of custom allocator

If I run the program, it will return SIGSEGV. If I dissasemble it and debug, I saw that it crash at begin of function dCAllocator::free().

#include <cstdlib>

class dCAllocator
{
public:
    void * alloc(unsigned long size)
    {
        return malloc(size);
    }
    void free(void * p)
    {
        free(p);
    }
};
int main()
{
    dCAllocator dalloc;
    int * arr = (int*)dalloc.alloc(sizeof(int)*40);
    for (int i=0; i<40; ++i)
        arr[i] = i*2;
    for (int i=0; i<40; ++i)
        cout << arr[i] << ", ";
    cout << endl;
    cout << "END" << endl;
    dalloc.free(arr);  // There is SIGSEGV
    cout << "OF DEALLOCATION" << endl;
    return 0;
}

Upvotes: 1

Views: 33

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

Your free() member will call itself until it runs out of stack space. You probably meant to call ::free():

void dCAllocator::free(void* ptr) {
    ::free(ptr);
}

Upvotes: 3

Related Questions