Click here to Skip to main content
12,506,733 members (56,619 online)
Click here to Skip to main content

Stats

58.7K views
464 downloads
49 bookmarked
Posted

Who deleted my pointer?

, 22 Apr 2003
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

k4_pacific
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?!).


You may also be interested in...

Pro
Pro
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160927.1 | Last Updated 23 Apr 2003
Article Copyright 2003 by k4_pacific
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid