GoldStrike
asked on
Stray Pointer??
This "appears" to work, I can run the code and get the desired result. After I add additional software modules, the system crashes.
class CStatus {
public:
STATUS setButtonRequest(const int*);
...
};
STATUS CStatus::setButtonRequest( const int* ipInButton)
{
SButtonRequest* pSInButtonRequest;
pSInButtonRequest->iButton ID = *(ipInButton);
}
struct SButtonRequest {
int iButtonID;
};
In order to fix the problem I do the following:
class CStatus {
public:
STATUS setButtonRequest(const int*);
SButtonRequest* pSInButtonRequest;
...
};
CStatus::CStatus()
{
pSInButtonRequest = new SButtonRequest;
}
STATUS CStatus::setButtonRequest( const int* ipInButton)
{
pSInButtonRequest->iButton ID = *(ipInButton);
}
I'm trying to figure out why I have to allocate space on the heap for the pointer to the object.
Why can't I localize the creation of the pointer in my method and have the storage be allocated and deallocated on the stack. Does anyone know why this fails?
Is there another way of doing this?
thanks for any help in understanding this problem.
class CStatus {
public:
STATUS setButtonRequest(const int*);
...
};
STATUS CStatus::setButtonRequest(
{
SButtonRequest* pSInButtonRequest;
pSInButtonRequest->iButton
}
struct SButtonRequest {
int iButtonID;
};
In order to fix the problem I do the following:
class CStatus {
public:
STATUS setButtonRequest(const int*);
SButtonRequest* pSInButtonRequest;
...
};
CStatus::CStatus()
{
pSInButtonRequest = new SButtonRequest;
}
STATUS CStatus::setButtonRequest(
{
pSInButtonRequest->iButton
}
I'm trying to figure out why I have to allocate space on the heap for the pointer to the object.
Why can't I localize the creation of the pointer in my method and have the storage be allocated and deallocated on the stack. Does anyone know why this fails?
Is there another way of doing this?
thanks for any help in understanding this problem.
Did you find this answer helpful at all?
If so it is time to grade it. Otherwise perhaps a clarifying question would help.
If so it is time to grade it. Otherwise perhaps a clarifying question would help.
ASKER
In the first example no SButtonRequest is ever created.
If this is the case why does the code work?
Is there another way of doing this without using the new statement?
If this is the case why does the code work?
Is there another way of doing this without using the new statement?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
That's the explanation I was hoping to get.
thanks
thanks
SButtonRequest* pSInButtonRequest;
This line merely creates a pointer to an SButtonRequest, but no SButtonRequest is created, nor is the pointer initialized to anything. In the second example though:
CStatus::CStatus()
{
pSInButtonRequest = new SButtonRequest;
}
An SButtonRequest structure is created, andpSInButtonRequest is initialized to point to it.