I hava some trouble understanding about guard flag in the following code.
// User-defined operator new.
void *operator new( size_t stAllocateBlock ) {
static int fInOpNew = 0; // Guard flag.
if ( fLogMemory && !fInOpNew ) {
fInOpNew = 1;
clog << "Memory block " << ++cBlocksAllocated
<< " allocated for " << stAllocateBlock
<< " bytes\n";
fInOpNew = 0;
}
return malloc( stAllocateBlock );
}
Anyone help to understand this ?
Thanks
EDIT: Thanks for clearing my doubt, and I understand this now. I got this code from here: https://msdn.microsoft.com/en-us/library/kftdy56f.aspx, they used same guard for delete also. Is the reason same ?
Please check my code, and share your suggestions to improve the code. Also, how to protect the code in multi threading with an example ? I would really appreciate this and it will clear my understanding about thread safe code, and also memory management very well.
Thanks
My version of code:
/*
* Memory leak detector
*/
#include <iostream> // for cout, clog
#include <new> // for size_t
using std::clog;
using std::cout;
/* Logging toggle, 0x0 - No, 0xFF - Yes */
char logMemory;
/* Number of Memory blocks allocated */
int memoryBlocksAllocated;
void* AllocateMemory(size_t size)
{
/*
* Guard flag for protecting from reentrancy (recursion),
* as clog also make use of new operator for
* allocating memory to the buffer.
*/
static char InOperationNew = 0x0;
if ( logMemory && !InOperationNew ) {
InOperationNew = 0xFF;
clog << "Memory block allocated " << ++memoryBlocksAllocated
<<" for requested size " << size << " bytes\n";
InOperationNew = 0x0;
}
return malloc(size);
}
void ReleaseMemory(void *ptr)
{
/*
* Guard flag for protecting from reentrancy (recursion),
* as clog also make use of new operator for
* allocating memory to the buffer.
*/
static char InOperationDelete = 0x0;
if ( logMemory && !InOperationDelete ) {
InOperationDelete = 0xFF;
clog << "Memory block deallocated " << memoryBlocksAllocated-- << "\n";
InOperationDelete = 0x0;
}
free(ptr);
}
/* User defined(overriden) global scope new operator */
void* operator new (size_t size)
{
return AllocateMemory(size);
}
/* User defined(overriden) global scope new[] array operator */
void* operator new[] (size_t size)
{
return AllocateMemory(size);
}
/* User defined(overriden) global scope delete operator */
void operator delete (void *ptr)
{
ReleaseMemory(ptr);
}
/* User defined(overriden) global scope delete[] array operator */
void operator delete[] (void *ptr)
{
ReleaseMemory(ptr);
}
int main()
{
logMemory = 0xFF; // Enable logging
// Allocate and destroy an array of objects
char *objArray = new char[2];
if ( objArray )
{
delete[] objArray;
}
else {
cout << "Memory allocation failed\n";
return -1;
}
// Allocate and destroy an object
char *obj = new char;
if ( obj )
{
delete obj;
}
else {
cout << "Memory allocation failed\n";
return -1;
}
logMemory = 0x0; // Disable logging
return 0;
}