c++ - 自定义分配器的奇怪行为

标签 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;
}

最佳答案

您的 free() 成员将调用自身,直到用完堆栈空间。您可能打算调用 ::free():

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

关于c++ - 自定义分配器的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22884500/

相关文章:

c++ - 异常安全——何时、如何、为什么?

c++ - 我可以阻止 std::sort 复制传递的比较对象吗

c++ - 错误 C244 '{' : missing function header (old-style formal list?) Visual C++

c++ - 当我更改函数内的参数时,调用者也会更改吗?

c++ - 编译器说定义的函数是虚拟的

c++ - 为什么在我的 C++ 代码中会抛出这个异常?

c++ - 基于 MFC 对话框的应用程序无法调用对话框两次

c++ - 将 json 对象转换为字符串 boost

c++ - 从 C 程序使用 C++ 共享对象?

c++ - 未解析的外部符号。 C++