Why could i get an Unhandled exception Access violation writing in c++/CLI?

Andy picture Andy · May 4, 2011 · Viewed 19.9k times · Source

I have been struggeling writing a solution excisting out of an c++ win32console and a c++ dll. i finally managed to get them talking without linker errors (so i am assuming both are fully managed c++/CLI projects) but when i run the console i get the following error.

Unhandled exception at 0x03f71849 in Company.Pins.Bank.Win32Console.exe: 0xC0000005: Access violation writing location 0x00000001.

The console also shows the following

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at wmain in c:...\win32console.cpp:line 20 at _wmainCRTStartup()

but i am assuming this is because of the unhandled exception.

tracking down this error as well as i can the error occurs when doing the return in the below code block. (the method linked by the return seems to step through fine, just when returning it seems to go bad.) Just in case you hadn't noticed, i did not write the below code myself, it was generated by visual studio.

#ifdef WPRFLAG
int wmainCRTStartup(
#else  /* WPRFLAG */
int mainCRTStartup(
#endif  /* WPRFLAG */

#endif  /* _WINMAIN_ */
        void
        )
{
        /*
         * The /GS security cookie must be initialized before any exception
         * handling targetting the current image is registered.  No function
         * using exception handling can be called in the current image until
         * after __security_init_cookie has been called.
         */
        __security_init_cookie();

        return __tmainCRTStartup();
}

#include "stdafx.h"
#include "UInstruction.h"

#define DllExport  __declspec(dllexport)
#define DllImport  __declspec(dllimport)

using namespace System;

edit: and the win32console.cpp code is below.

//int main(array<System::String ^> ^args)
int _tmain(int argc, _TCHAR* argv[])
{
    auto P2 = (TCHAR *)"3 Barrowstead";
    TCHAR* P3 = (TCHAR *)"3 Barrowstead";
    double* P1;
    P1[0] = 13;

    UserInstruction(P1, P2, P3);
}

Answer

James McNellis picture James McNellis · May 4, 2011

You declare a pointer and do not initialize it so it doesn't point at an object (it contains some garbage address):

double* P1;     

Then you try to write to wherever this uninitialized pointer points:

P1[0] = 13;

You cannot use an uninitialized variable. You need to initialize P1 to point at some object before you dereference it.