如果我运行该程序,它将返回 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;
}
最佳答案
您的 free()
成员将调用自身,直到用完堆栈空间。您可能打算调用 ::free()
:
void dCAllocator::free(void* ptr) {
::free(ptr);
}
关于c++ - 自定义分配器的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22884500/