自定义分配器的奇怪行为

时间:2014-04-05 17:49:57

标签: c++

如果我运行该程序,它将返回SIGSEGV。如果我将它解散并进行调试,我看到它在函数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;
}

1 个答案:

答案 0 :(得分:3)

您的free()成员将自行调用,直到它的堆栈空间不足为止。您可能打算致电::free()

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