char *mem = "not on the heap!";
free(mem);
unsigned char *mem = (unsigned char*)malloc(100);
mem++;
free(mem); // mem has wrong address!
由于 mem 的值在递增后不再是 64 字节对齐,因此健全性检查可以轻松看出它不可能是堆指针!
struct A {
int a = 0;
~A() {// destructor is not trivial!
std::cout << a << "\n";
}
};
A *mem = new A[10];
delete mem;
当new 数组对象时,前4个字节保存的是此对象数组中对象的个数。
new[]/delete[] 与 new/delete的区别
unsigned char *mem = (unsigned char*)malloc(10);
free(mem);
free(mem); # the pointer is already freed
struct A {// bad: doesn't adhere to rule of three
int* ptr;
A(int i): ptr(new int(i))
{
}
~A()
{
delete ptr;
}
};
{
A a(0);
A b = a; // a and b share pointer: a.ptr == b.ptr
} // here destructors of b and a called => problem
// at first b.ptr gets deleted
// deleting (already deleted) a.ptr leads now to UB/error.
_CtrlsValidHeapPointer(block)