Click here to Skip to main content
15,892,298 members
Articles / Desktop Programming / MFC

Who Deleted My Pointer?

Rate me:
Please Sign up or sign in to vote.
4.93/5 (32 votes)
22 Apr 20034 min read 69.1K   493   49  
Locating your dangling pointer with overloaded new and delete operators
#include <malloc.h>

void * ::operator new(size_t size)
{
	int stackVar;
	unsigned long stackVarAddr = (unsigned long)&stackVar;
	unsigned long argAddr = (unsigned long)&size;

	void ** retAddrAddr = (void **)(stackVarAddr/2 + argAddr/2 + 2);

	void * retAddr = * retAddrAddr;

	unsigned char *retBuffer = (unsigned char*)malloc(size + 16);

	memset(retBuffer, 0, 16);

	memcpy(retBuffer, &retAddr, sizeof(retAddr));

	memcpy(retBuffer + 4, &size, sizeof(size));

	return retBuffer + 16;
}

void ::operator delete(void *buf)
{
	int stackVar;
	if(!buf)
		return;

	unsigned long stackVarAddr = (unsigned long)&stackVar;
	unsigned long argAddr = (unsigned long)&buf;

	void ** retAddrAddr = (void **)(stackVarAddr/2 + argAddr/2 + 2);

	void * retAddr = * retAddrAddr;

	unsigned char* buf2 = (unsigned char*)buf;

	buf2 -= 8;

	memcpy(buf2, &retAddr, sizeof(retAddr));

	size_t size;

	buf2 -= 4;

	memcpy(&size, buf2, sizeof(buf2));

	buf2 += 8;

	buf2[0] = 0xde;
	buf2[1] = 0xad;
	buf2[2] = 0xbe;
	buf2[3] = 0xef;


	buf2 += 4;

	memset(buf2, 0x7777, size);

//  deallocating destroys saved addresses, so don't
//	buf -= 16;
//	free(buf2);
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


Written By
Web Developer
United States United States
I was born and raised in Dayton, Ohio. I acquired an NCR PC Model 4 when I was 8, and was writing fairly complex GW-BASIC programs by the time I was ten. Educated formally at Wright State University, I now work for an undisclosed company doing platform level work with Linux, Windows, and, sadly still, DOS (Why the &%^& won't [name withheld] %^&%$%# upgrade already?!).


Comments and Discussions