devxlogo

Debug-friendly New and Delete

Debug-friendly New and Delete

For better handling of resource leaks, try “marking” the allocation with ancillary information:

#include #include #include #include typedef void FDEL(void* p, size_t size);typedef FDEL* PFDEL;class A{	int a;	static void sfree(void* p, size_t size);	static void sfreedebug(void* p, size_t size);public:	virtual ~A() {}	void* operator new(size_t size);	void operator delete(void* p, size_t size);	void* operator new(size_t size,  char* Tag); };void A::operator delete(void* p, size_t size){	char* pb = (char*) p;	pb -= sizeof(PFDEL);	PFDEL pfdel = *(PFDEL*)pb;	(*pfdel)(pb, size);}void A::sfree(void* p, size_t size){	free(p);}void* A::operator new(size_t size){	char* pb = (char*) malloc(size + sizeof(PFDEL));	*(PFDEL*)pb = &sfree;	return (pb + sizeof(PFDEL));}struct DEBUGHDR{	size_t size;	char* Tag;	PFDEL pfdel;};void A::sfreedebug(void* p, size_t size){	char* pb = (char*) p;	pb += (sizeof(PFDEL) - sizeof(DEBUGHDR));	DEBUGHDR* phdr = (DEBUGHDR*) pb;	assert(size == phdr->size);	cout size 	     Tag size = size;	phdr->Tag= Tag;	phdr->pfdel = &sfreedebug;	cout size 		Tag 
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist