Is it possible to zero out the memory of deleted objects in C++? I want to do this to reproduce a coredump in unit test:
//Some member variable of object-b is passed-by-pointer to object-a
//When object-b is deleted, that member variable is also deleted
//In my unit test code, I want to reproduce this
//even if I explicitly call delete on object-b
//accessBMemberVariable should coredump, but it doesn't
//I'm assuming even though object-b is deleted, it's still intact in memory
A *a = new A();
{
B *b = new B(a);
delete b;
}
a->accessBMemberVariable();
You probably should override the delete
operator.
Example for the given class B:
class B
{
public:
// your code
...
// override delete
void operator delete(void * p, size_t s)
{
::memset(p, 0, s);
::operator delete(p, s);
}
};
EDIT: Thanks litb for pointing this out.
accessBMemberVariable should coredump, but it doesn't
Nah, why should it? It's quite possible that the memory that b used to occupy is now owned by the CRT, the CRT that your application owns. The CRT may opt to not release memory back to the OS. Core dumps will only happen if you access memory not owned by your application.
Zeroing out the memory occupied by b may not do you any good depending on the type of variable that A has the address of.
My advice would be to allocate B on the stack, that should bring out the fireworks... but then again, not quite in the way you'd expect...
So if you really want a core dump you should use the OS functions to allocate memory and free it:
char *buf = OS_Alloc(sizeof(B));
B *b = new(buf) B();
a->someBMember = &b->myMember;
b->~B();
OS_Free(buf);
a->accessBMemberVariable();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With