customerize operater new to detect memory underrun and overruns
Jan 11, 2010 at 11:12am UTC
Hi folks,
I am looking at the following pseudocode:
1 2 3 4 5 6 7 8 9 10 11 12 13
static const int signature = 0xDEADBEFF;
typedef unsigned char Byte;
void * operator new (size_t size) throw (std::bad_alloc)
{
using namespace std;
size_t realSize = size + 2 * sizeof (int );
void * pMem = malloc(realSize);
if (!pMem) throw bad_alloc();
*(static_cast <int *>(pMem) ) = signature;
*(reinterpret_cast <int *>(static_cast <Byte*>(pMem) + realSize - sizeof (int ))) = signature;
return static_cast <Byte*>(pMem) + sizeof (int );
}
Since the memory has been allocated in terms of std::size_t (the malloc statement on line 7), can I simply NOT typedef unsigned char as Byte and use std::size_t instead? So my pseudocode looks like this:
1 2 3 4 5 6 7 8 9 10 11 12
static const int signature = 0xDEADBEFF;
void * operator new (size_t size) throw (std::bad_alloc)
{
using namespace std;
size_t realSize = size + 2 * sizeof (int );
void * pMem = malloc(realSize);
if (!pMem) throw bad_alloc();
*(static_cast <int *>(pMem) ) = signature;
*(reinterpret_cast <int *>(static_cast <std::size_t*>(pMem) + realSize - sizeof (int ))) = signature;
return static_cast <std::size_t*>(pMem) + sizeof (int );
}
Cheers,
Robert
Last edited on Jan 11, 2010 at 11:31am UTC
Jan 11, 2010 at 1:17pm UTC
some_ptr + sizeof( int )
yields different addresses, depending upon the type of some_ptr, so I would say that lines 11 and 12 in the original
code do something different than lines 10 and 11 in the new code.
Topic archived. No new replies allowed.