Re: Quick question...
"Robby" <Robby@discussions.microsoft.com> wrote in message
news:519F4FA0-D11C-4CA3-91C3-A627A6A78A9E@microsoft.com...
Can we create a class with some of its members residing on the stack and
some residing on the heap.
Careful - "itsAge" is the member and it is a pointer. If you use
itsAge = new ...;
then it points to the allocated buffer. If you don't then it will point
somewhere dangerously random. In either case itsAge is the member and what
it points at isn't.
Please consider the following code:...
It's bad news on several counts.
If you use "delete itsAge" in the destructor, then you had better be sure
that itsAge has either been set to point to something you can destroy (by
allocating with new) or is NULL. Cat::Cat(int Boxes) does neither, but
leaves a random pointer. Cat::setAge(int age) will also be a disaster
because of this and Cat::getAge() will at best return junk.
The constructor with the integer argument must set up itsAge or you're in
trouble. The error message isn't vague (though it may be opaque). It is
telling you that you are trying to delete something you're not entirlted to.
Dave
--
David Webber
Author MOZART the music processor for Windows -
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm
================================================
class Cat
{
public:
Cat(); //Default constructor
Cat(int Boxes); //Constructor
~Cat(); //Destructor
int getAge();
void setAge(int age);
private:
int *itsAge; //Created on the free store
int SandBoxes; //Created on the stack
};
//Constructor
Cat::Cat()
{
itsAge = new int(2);
}
//Constructor for object on stack
Cat::Cat(int Boxes)
{
SandBoxes = Boxes;
}
//Destructor
Cat::~Cat()
{
delete itsAge;
}
int Cat::getAge()
{
return *itsAge;
}
void Cat::setAge(int age)
{
*itsAge = age;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
Cat *pCat = new Cat;
Cat xxx(22);
WM_PAINT:
pCat->setAge(99);
GetLastAge = pCat->getAge();
TextOut(hdc,100,300,
M_szBuffer,wsprintf(M_szBuffer,TEXT("%d"),GetLastAge));
return 0;
...Some other code....
====================================================
This code unfortunately doesn't even give an error at compile or build
time.
However when I go to start it, it breaks and displays a "Microsoft
Development environment" window and says a vague message:
"Unhandled exception at 0X00412e28 in APP_.exe: OC0000005: Access
violation
reading location 0Xccccccc0."
When I click on "Break" button of this window, it closes ansd a yellow
arrow
pointing to the following line:
/* verify block type */
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
in dbgdel.cpp file, which is not one of mine!
The program can work if I remove the following line though:
Cat xxx(22);
Can someone help me understand this problem, All sugestions are much
apreciated!
--
Best regards
Robert