tags:

views:

37

answers:

2

I have a C++/CLI (VS 2008) mixed mode library that creates native objects and calls methods in then. Native dll is written in pure c++. Now in my C++/CLI wrapper methods if I declare object of native classes in c++ way as

ClassA obj;
Obj.Method(); 

and use it, it works but, I get System.AccessViolationException: Attempt to read or write protected memory when the program exists.

But if I do it this way

ClassA *obj = new ClassA();
Obj->Method();

it works fine. So my question is why cant I declare a object just on stack the C++ way ? Destructor in the native code is declared virtual. Is that the reason ?

A: 

My guess is your destructor has an error in it. When the program exits your destructor goes off in the first case, but not in the second. You could test this by adding

delete obj;

somewhere in your second-case code, and stepping with the debugger to see if you get the exception. Then solve the problem in your destructor.

Kate Gregory
I tried debugginb in that angle, delete works for the second case.And calling destructor dint create any errors. I wrote a native sample as well to test it.
anivas
A: 

No, this has nothing to do with stack vs heap. The stack in a managed program is no different from one in a native program. Using native code in a managed program doesn't make it any less likely to cause it to destroy the heap, stomp the stack frame, overwrite the end of a buffer, invoke undefined behavior, the usual stuff that make native code crash with an access violation.

The difference between storing it on the stack vs the heap is the kind of damage that's done. Yes, heap corruption can take a while to have side-effects. Usually much longer than stack frame corruption, including never.

Hans Passant