How Can I Debug an Access Violation?

 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at How Can I Debug an Access Violation?.

Problem Description
My program produces an access violation. How can I debug this?

If you get an access violation on a line of code that dereferences multiple pointers, it can be difficult to find out which pointer caused the access violation. Starting in Visual Studio 2015 Update 1, the exception dialog box now explicitly names the pointer that caused the access violation.

For example, given the following code, you should get an access violation:

#include <iostream>  
using namespace std;  
  
class ClassB {  
public:  
        ClassC* C;  
        ClassB() {  
                C = new ClassC();  
        }  
     void printHello() {  
                cout << "hello world";  
        }  
};  
  
class ClassA {  
public:  
    ClassB* B;  
      ClassA() {  
                B = nullptr;  
        }  
};  
  
int main() {  
    ClassA* A = new ClassA();  
      A->B->printHello();  
}  

If you run this code in Visual Studio 2015 Update 1, you should see the following exception dialog:

AccessViolationCPlus

If you cannot determine why the pointer caused an access violation, trace through the code to make sure that the pointer causing the problem has been assigned correctly. If it is passed as a parameter, make sure that it is passed correctly, and you aren’t accidentally creating a shallow copy. Then verify that the values are not being unintentionally changed somewhere in the program by creating a Data Breakpoint for the pointer in question to make sure it isn’t being modified elsewhere in the program. For more information about data breakpoints, see the data breakpoint section in Using Breakpoints.

Debugging Native Code FAQs

Show: