chaitanyakrishna
chaitanyakrishna

Reputation: 86

MFC "memory allocation violation"

I created a check box in a dialog box and trying to access its condition whether checked or not. This is my code:

CButton *m_ctlCheckBlack = (CButton *)GetDlgItem(IDC_BLACK);

int chkBoxBlack = m_ctlCheckBlack->GetCheck();

As I run through this code, it pops up an exception saying :

Exception thrown at 0x0FA45564 (mfc140d.dll) in braille_obr.exe: 0xC0000005:      
Access violation reading location 0x00000020.

any help will be appreciated. thank you.

Upvotes: 0

Views: 610

Answers (2)

nariuji
nariuji

Reputation: 278

Perhaps, I doubt it tried to get the state of button when the Button was not yet constructed.

int chkBoxBlack = m_ctlCheckBlack != NULL ? m_ctlCheckBlack->GetCheck() : 0;

Or, do you try to operate from outside dialog? If it is so, you had better try to do this.

■CButton *m_ctlCheckBlack = (CButton *)yourdlg.GetDlgItem(IDC_BLACK);

■FindWindowEx(yourdlg.GetSafeHwnd(), NULL, NULL, "(your button caption)");

Upvotes: 0

lakeweb
lakeweb

Reputation: 1939

There is rarely a good reason to use GetDlgItem. In your resource editor, right click the button and 'Add Variable..' It will default as a control. Give it a name. You will get a member in the dialog class:

CButton myButtonName;

Now it should be safe to:

myButtonName.GetChecked( );

as it will have been created and properly subclassed.

Upvotes: 1

Related Questions