Error: -1073741813 [ C0000005 - access violation exception ], when running a custom C++ application

Joseph RW 105 Reputation points
2023-07-13T08:46:12.2666667+00:00

Hi Microsoft team,

I am new to C++ and have never experienced this issue before, I am following the Sektor 7 courses, and whilst trying to accomplish one of the coding tasks, I have come across this issue - Error: -1073741813, If it helps - the application is built on a windows 11 home edition host machine using visual studio 2022, but the program is executed on a separate computer within a Windows 10 Vagrant VM running on a Linux Host.

This is the C++ code:


#include <windows.h>
#include <winternl.h>
#include <iostream>

typedef NTSTATUS(NTAPI* pNtOpenProcess)(PHANDLE ProcessHandle, ACCESS_MASK AccessMask, POBJECT_ATTRIBUTES ObjectAttributes, CLIENT_ID* ClientId);

int main(int argc, char* argv[]) {
    // argc is the number of arguments. 
    // argc will be at least 1 because the program's name is always the first argument.

    // argv is an array of char pointers (C-style strings).
    // argv[0] is the program's name, argv[1] is the first argument, argv[2] is the second argument, etc.

    if (argc < 2) {
        // If no argument was supplied, print an error message
        std::cerr << "No argument was provided." << std::endl;
        return 1;
    }

    // Print out the first argument
    std::cout << "The first argument is: " << argv[1] << std::endl;

    char* processId = argv[1];

    if (processId == 0) {
        std::cerr << "Could not find process.";
        return 1;
    }

    // Load ntdll.dll, which contains NtOpenProcess
    HMODULE hNtDll = LoadLibrary(TEXT("ntdll.dll"));
    if (!hNtDll) {
        std::cerr << "Could not load ntdll.dll.";
        return 1;
    }

    // Get the address of NtOpenProcess
    pNtOpenProcess NtOpenProcess = (pNtOpenProcess)GetProcAddress(hNtDll, "NtOpenProcess");
    if (!NtOpenProcess) {
        std::cerr << "Could not get the address of NtOpenProcess.";
        return 1;
    }
    CLIENT_ID cid;
    cid.UniqueProcess = (HANDLE)(ULONG_PTR)processId;  // Cast to ULONG_PTR first to suppress warning C4312
    cid.UniqueThread = 0;  // Zero for no specific thread

    OBJECT_ATTRIBUTES oa;
    ZeroMemory(&oa, sizeof(OBJECT_ATTRIBUTES));
    oa.Length = sizeof(OBJECT_ATTRIBUTES);


    // Get a handle to the process
    HANDLE hProcess;
    NTSTATUS status = NtOpenProcess(&hProcess, PROCESS_ALL_ACCESS, &oa, &cid);
    if (status < 0) {
        std::cerr << "NtOpenProcess failed with status: " << status;
        return 1;
    }
    else {
        std::cerr << "NtOpenProcess opened successfully: " << status;

    }

    // At this point, you have a handle to the process and you can use it for further manipulations.
    // For instance, you can read/write memory, create threads, etc.

    // Don't forget to close the handle once you're done!
    CloseHandle(hProcess);

    return 0;
}
  1. This are the CLI commands used to run the program, Get the process ID of notepad

PS C:\Users\vagrant\Desktop\DEVELOPMENT_ENV_files\v2_final> (Get-Process -Name notepad).Id

3560

  1. Run the program supplying the notepad process ID as an argument

PS C:\Users\vagrant\Desktop\DEVELOPMENT_ENV_files\v2_final> .\ConsoleApplication1.exe 3560

The first argument is: 3560

NtOpenProcess failed with status: -1073741813

Here is a screenshot of the output.

Screenshot 2023-07-12 233804

Chat GPT gave me this ->

The status code -1073741813 is a hexadecimal C0000005, which corresponds to an access violation exception, also known as a segmentation fault. This typically happens when a program tries to read or write to a memory area it doesn't have access to.

In the context of NtOpenProcess, this error might occur due to a few reasons:

Incorrect Process ID: The Process ID you're passing to NtOpenProcess might be incorrect or the process might not exist anymore.

Access Rights: Your process might not have the necessary privileges to open the target process. Make sure you have the necessary permissions. In some cases, you might need to run your program as an administrator to have sufficient privileges.

Bad Pointers: If you're passing incorrect pointer values to NtOpenProcess, it might lead to an access violation. Make sure OBJECT_ATTRIBUTES and CLIENT_ID structures are properly initialized before passing them to the function.

I have also tried modifying certain areas of the code like this, but without any luck.

    CLIENT_ID cid;
    cid.UniqueProcess = (HANDLE)(ULONG_PTR)processId;  // Cast to ULONG_PTR first to suppress warning C4312
    cid.UniqueThread = 0;  // Zero for no specific thread

    OBJECT_ATTRIBUTES oa;
    ZeroMemory(&oa, sizeof(OBJECT_ATTRIBUTES));
    oa.Length = sizeof(OBJECT_ATTRIBUTES);

I have followed all of the steps mentioned above and there does not seem to be an Issue with my code as I have set the VS Studio debug level to 4 and the code compiles without any errors or warnings.

2

Any help will be greatly appreciated.

Thank You

regards

Joseph.

Developer technologies | Visual Studio | Debugging
Windows for business | Windows Client for IT Pros | User experience | Other
Developer technologies | C++
Developer technologies | 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.

Developer technologies | Visual Studio | Other
Developer technologies | Visual Studio | Other

A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.


Answer accepted by question author

RLWA32 52,576 Reputation points
2023-07-13T09:21:58.42+00:00

The handling of the process id parameter is incorrect.

Try this after also including the cstdio header file -

    CLIENT_ID cid;
    cid.UniqueProcess = (HANDLE)(ULONG_PTR)atol(argv[1]); // convert string to numeric value
    //cid.UniqueProcess = (HANDLE)(ULONG_PTR)processId;  // Cast to ULONG_PTR first to suppress warning C4312
    cid.UniqueThread = 0;  // Zero for no specific thread
    


    ```

Was this answer helpful?

1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Limitless Technology 45,246 Reputation points
    2023-07-13T12:29:29.8433333+00:00

    Hello there,

    The error message you provided, "-1073741813 [C0000005 - access violation exception]," indicates an access violation exception in your custom C++ application. This exception typically occurs when a program attempts to access a memory location that it either does not have permission to access or that does not exist.

    Here are a few common causes and potential solutions for this error:

    Null or uninitialized pointers: Check if any pointers in your code are uninitialized or set to null when they should be pointing to valid memory locations. Ensure that all pointers are properly initialized before they are accessed.

    Out-of-bounds array access: Verify that you are not accessing array elements beyond their bounds. Make sure your array indices are within the valid range.

    Memory leaks: Ensure that you are managing memory properly in your code, including allocating and freeing memory correctly. Failing to deallocate memory or accessing already deallocated memory can lead to access violation exceptions.

    Incorrect memory usage: Double-check if you are using memory correctly, such as not accessing dangling pointers or using memory after it has been freed.

    I used AI provided by ChatGPT to formulate part of this response. I have verified that the information is accurate before sharing it with you.

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.