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

微笑、不失礼 提交于 2019-12-04 15:31:42

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.

double* P1;

is uninitialized. You then attempt to set its first entry to 13. Boom, access violation, or worse.

Any of these snippets should work:

double P1;
P1 = 13;
UserInstruction(&P1, P2, P3);

or

double P1[1];
P1[0] = 13;
UserInstruction(P1, P2, P3);

or

double *P1 = new double[1];
P1[0] = 13;
UserInstruction(P1, P2, P3);
delete[] P1;

The following statements are also wrong when using UNICODE build:

  auto P2 = (TCHAR *)"3 Barrowstead";
  TCHAR* P3 = (TCHAR *)"3 Barrowstead"; 

because you're casting a normal (char) array to a wchar_t pointer.

if you build with UNICODE then you should change these in:

  LPCTSTR P2 = _T("3 Barrowstead");
  LPCTSTR P3 = _T("Barrowstead"); 

It is undefined behaviour to convert a string literal to a TCHAR*, as if UNICODE is defined then TCHAR* will become wchar_t*, and a string literal is not a wchar_t* and this pointer conversion is undefined.

fabio dias

I managed to find error the following way:

  • It was not in the line that the error poped-up.
  • It was actually in the last location I have PIN_PTR the memory.

I have used the following to copy a vector:

memcpy(&pined_ptr[0],&unmanagedvector[0],sizeofunmanagedvector);

The problem was PINED_PRT SIZE < unmanagedVectorSize ! Stupid error.

This messed up all managed memory, an expoded couple of lines & functions later.

How you can find in your code: Go disableling ranges of the code, until your code does not crash.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!