Skip to main content
gamedev.net
🔒 Locked

allocating Memory query?

Started by themadme Aug 26, 2011 at 12:14 PM 2 replies 1.3k views
Original Post
themadme
themadme
Hello everyone,

This may be a naive question but what are the dangers of the following code,(allocate more memory in the new operator for the info struct):




struct Info
{
Info():nLineNo(0){memset(cFile, 0, 256);}
~Info(){}
char cFile[256];
unsigned int nLineNo;
};


void *operator new(size_t Size, const char *pcFile, const unsigned int nLine)
{
Info *pData = 0;

pData = (Info*)malloc(Size + sizeof(Info));

strcpy(pData->cFile, pcFile);

pData->nLineNo = nLine;

return (void*)pData;
}


void operator delete(void *pData)
{
Info *pInfo = (Info*)pData;
// could use pInfo->nLineNo to check for it within hash table of allocated blocks - just an example
free(pData);
}



Just wondering if this bad idea to do.

Many thanks for reading.
ryan20fun
ryan20fun
why not just use ?

#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
Never say Never, Because Never comes too soon. - ryan20fun

Disclaimer: Each post of mine is intended as an attempt of helping and/or bringing some meaningfull insight to the topic at hand. Due to my nature, my good intentions will not always be plainly visible. I apologise in advance and assure you I mean no harm and do not intend to insult anyone.
Adam_42
Adam_42
What you need to do to make it have any chance of working reliably is to adjust the address you return so the allocated object and your info structure won't be sharing the same memory. Firstly do "return (void*)(pData + 1);" in the new operator. You then need to do the reverse in the delete: "Info *pInfo = ((Info*)pData) - 1; free(pInfo);"

Also (assuming pcFile comes from the __FILE__ macro) you can save yourself loads of memory by changing the char[256] to a char* and storing the pointer to the string.

In addition the constructor and destructor on that Info struct will never be called by the posted code since you allocate their memory with malloc(). I'd delete them.
themadme
themadme
thanks for the replies and the answers you gave were exactly what I was hoping for.

The above code was just a small example, i do have
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)

And i will be adjust the address i return. In fact im going to have a memory manager class that will have already allocated a huge block and will return a block of memory.

Again thanks for the replies

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.