Jump to content
  • Advertisement
Sign in to follow this  
ShadowPhoenix

MyMemory - a malloc wrapper [C++]

This topic is 3730 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Now, I created this very nice class to manage all my mallocs and to tell me how much memory I am using and how many calls were made. However, I want to create a global function called xmalloc which will use this class to malloc. How do I do that? Do I just create a void* xmalloc(size_t size); in a new file and reference the file as first everywhere?
/*
			Memory.h - Manages malloc calls so that null gets reported and also counts calls.

*/





#pragma once

#include "stdafx.h"




class Memory{  // Safe class, attempts to save file after every r/w 
	
public:
Memory();
~Memory();
void *xmalloc(size_t size);
void xfree(void *pointer);
void reportMem(char * buffer,int size); // buffer = buffer, size = max size, in BYTES



private: 
char emergencyMemory[64]; // when malloc fails we can't call malloc anymore. Thus, we use stack.

long double totalBytes;
long double totMallocReq;
long double totFreed;

std::ofstream logger;

#ifdef DEBUG
struct infoPtr{void* ptr;size_t size;size_t timeAlloc;};
std::list<infoPtr> ptrList;
std::list<infoPtr>::iterator myIter;
#endif
};


const Memory myMemory;


/*
			Memory.cpp

*/


#include "Memory.h"
#include "stdafx.h" // fine....


#define _CRT_SECURE_NO_WARNINGS 1

using namespace std;
Memory::Memory()
{
	memset((void*)this,0,sizeof(Memory));
totalBytes=0;
totMallocReq=0;
totFreed=0;
logger.open("Logs//Memory.txt",ofstream::trunc); 
logger &lt;&lt; "[INFO] Starting a critical sub-system of memory." &lt;&lt;endl;
logger &lt;&lt; "       If this fails, then please locate the closest exit," &lt;&lt; endl;
logger &lt;&lt; "       and exit in a properly fashion" &lt;&lt; endl;

logger.flush();
}

Memory::~Memory()
{
	logger &lt;&lt;"[INFO] Closing memory managment."&lt;&lt;endl;
	logger.flush();

	char *buff=(char*) malloc(256*sizeof(char));
	reportMem(buff,256*sizeof(char));
	logger &lt;&lt; buff;
	logger.flush();
	if(totalBytes!=0)
		logger &lt;&lt; "We got some UNFREED RAM, as reported by total bytes !=0"&lt;&lt;endl;
	logger.flush();
	logger.close();
}

void* Memory::xmalloc(size_t size)
{
void* ptr = malloc(size);
if(ptr==null)
	{
		logger &lt;&lt; "ERROR, CRITICAL ERROR HAS JSUT OCCURED. MALLOC FAILED - MALLOC FAILED" &lt;&lt; endl;
		logger.flush();
		logger &lt;&lt; "THE FAILING OCCURED with the following RAM use (Requested Bytes.total Malloc Requests. total Freed.";
		logger.flush();
		reportMem(emergencyMemory,64*sizeof(char));
		logger &lt;&lt; emergencyMemory &lt;&lt; endl;
		logger.flush();
		return NULL; // I feel bad feeding NULL. Maybe reserve some ram before hand?
	}
totalBytes+=size;
totMallocReq++;

#ifdef DEBUG
infoPtr myStr={ptr,size,(size_t)time(NULL)};
ptrList.push_front(myStr);
#endif

return ptr;

}


void Memory::xfree(void *pointer)
{
	if(pointer=NULL)
	{logger &lt;&lt; "[WEIRD ERROR: NULL POINTER] THIS POINTER IS NULL. NOTHING DONE." &lt;&lt; endl;
	return;}
	
free(pointer);
totFreed++;
#ifdef DEBUG
void *tmp=NULL;
myIter = ptrList.begin();

while(tmp!=pointer)
tmp=(*myIter++).ptr;

totalBytes-=(*myIter).size;
#endif
}


void Memory::reportMem(char * buffer,int size)
{
	int bytes;
 bytes=sprintf_s(buffer,12*sizeof(char),"%E",totalBytes);
buffer[bytes]='.';

 if(bytes&gt;=size)
	 return;

bytes+=sprintf_s(buffer,12*sizeof(char),"%E",totMallocReq);
buffer[bytes]='.';

if(bytes&gt;=size)
	 return;

bytes+=sprintf_s(buffer,12*sizeof(char),"%E",totFreed);
	 buffer[bytes]='.';
	 buffer[bytes+1]='\n';

}


#undef _CRT_SECURE_NO_WARNINGS





Share this post


Link to post
Share on other sites
Advertisement
You are aware of the problems with using malloc in C++, right? Mainly, you should not use it, since constructors will not be called.

What you'd want to replace is new and delete, and this is rather nontrivial to do well. You're probably better off using an existing management tool like Paul Nettle's mmgr, rather than trying to roll your own. There are already quite a few serious bugs in your implementation (memsetting this, using = when you meant ==, using classes that themselves allocate memory, et cetera).

Share this post


Link to post
Share on other sites
You need to perform some macro magic like Paul Nettle's do (look in Ogre3D's MemoryManager to get an overview of his manager).

I have also recently created a custom MemoryManager for my own projects, although mine is far more complex and with options for substitution of *alloc, free, new and delete plus a custom STL allocator. And although it provides my projects with everything I have ever needed from such a module, it was far from trivial to get right and took a couple of tedious revisions, since the macro trickery combined with the custom allocation routines was source of numerous, various errors in different situations and/or projects.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!