gpt4 book ai didi

c++ - 运算符删除导致堆损坏,而运算符新工作正常

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:22:19 30 4
gpt4 key购买 nike

我已经让 operator new 工作了,但是当我调用 delete 时,它​​在 free (ptr) 行崩溃了。任何人都可以告诉我在这个基类中重载 operator new 和 delete 时我做错了什么吗?提示:我不是在问设计问题。

class Base {
private:
int i;

public:
Base () : i (10) {
}

static void * operator new (size_t size) {
if (size = 0) size = 1; // please read this line carefully! size = 0!
return malloc (size);
}

static void operator delete (void *ptr, size_t size) {
if (ptr == NULL) return;
free (ptr);
}
};

最佳答案

这对我有用:

#include <cstdlib>
using namespace std;
class Base {
public:
void * operator new(size_t size) {
if (size == 0) size = 1;
return malloc (size);
}

void operator delete (void *ptr, size_t size) {
if (ptr == NULL) return;
free (ptr);
}
};

int main()
{
Base* b = new Base;
delete b;
return 0;
}

hank@tardis:/tmp$ g++ -o test test.cpp 
hank@tardis:/tmp$ ./test
hank@tardis:/tmp$ valgrind ./test
==7229== HEAP SUMMARY:
==7229== in use at exit: 0 bytes in 0 blocks
==7229== total heap usage: 1 allocs, 1 frees, 1 bytes allocated
==7229==
==7229== All heap blocks were freed -- no leaks are possible
==7229==
==7229== For counts of detected and suppressed errors, rerun with: -v
==7229== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)

关于c++ - 运算符删除导致堆损坏,而运算符新工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4290509/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com