[C++] Exception thrown: read access violation. **this** was nullptr.

Eric Tian 211 Reputation points
2020-11-23T00:56:27.29+00:00

Hello,

I have a settings page with a "back" button. When It is clicked, it calls the "CollapseFrame" method in MainPage.xaml. That method collapses the frame containing the Settings Page. However, when debugging, I received this error: "Exception thrown: read access violation. this was nullptr":

void MainPage::CollapseSettings()
{
    SettingsHolder->Visibility = ::Visibility::Collapsed; // This line is where I encountered the error.
}
Universal Windows Platform (UWP)
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,544 questions
{count} votes

Accepted answer
  1. Yan Gu - MSFT 2,676 Reputation points
    2020-11-24T07:40:29.717+00:00

    Hello,

    Welcome to Microsoft Q&A.

    The instance of SettinsPage created in MainPage::MainPage() is not the instance of SettingsPage contained by frame SettingsHolder. Therefore, the statement s->ParentMainPage = this; does not work for the instance of SettingsPage contained by frame SettingsHolder and the ParentMainPage is null.

    You could initiate the value of ParentMainPage in OnNavigatedTo() method with the parameter e which contains the parameter passed from Frame.Navigate(Type,Object) method.

    For example:

    MainPage.xaml.cpp

    //Show the SettingsPage page in frame SettingsHolder by using Navigate method  
    SettingsHolder->Navigate(TypeName(SettingsPage::typeid),this);  
    

    SettingsPage.xaml.h

       protected:  
              virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;  
    

    SettingsPage.xaml.cpp

    void AccessViolation::SettingsPage::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)  
    {  
           MainPage^ mainPage = (MainPage^)e->Parameter;  
           if (mainPage != nullptr)  
           {  
                  ParentMainPage = mainPage;  
           }  
    }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful