다음을 통해 공유


How Can I Debug an Access Violation?

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

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

Solution

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.

See Also

Debugging Native Code FAQs