Link to home
Start Free TrialLog in
Avatar of GoldStrike
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->iButtonID = *(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->iButtonID = *(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.
Avatar of imladris
imladris
Flag of Canada image

In the first example no SButtonRequest is ever created.

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.
Did you find this answer helpful at all?

If so it is time to grade it. Otherwise perhaps a clarifying question would help.
Avatar of GoldStrike
GoldStrike

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?
ASKER CERTIFIED SOLUTION
Avatar of imladris
imladris
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That's the explanation I was hoping to get.

thanks