Search code examples
c#c++pointersinteropaccess-violation

How to best handle unused pointer when calling C++ from C#?


I have code in C++, which I will call from C# via interop mechanism.

In my C++ code, this is my class structure

extern "C" struct __declspec(dllexport) LegList
{
    SimpleList          simple_List;
    int*                inputList;
};

This is my C# code:

[StructLayout(LayoutKind.Sequential)]
public struct LegList
{
   SimpleList           simple_List;    
    public IntPtr inputList;

}

The inputList is not used anywhere in C#.

My questions are:

  1. In C++ code, should I set inputList to NULL?
  2. If I set it to NULL, how should I best set it to avoid bugs? Should I use inputList=0, or inputList=NULL, or inputList=(int*)malloc(0)?
  3. If I don't set it, or if I set it wrongly, what are the consequences? Will some very hard to diagnose bug appears? What I am afraid is that if I don't set it correctly, some machines might run the code fine, others might not. And when the program stops working, it will stop at a point much later, resulting in a very hard to diagnose problem for us, such as AccessViolationException.
  4. All in all, if I set it to inputList=(int*)malloc(0), or if I don't set it at all, will the program crash at a different place at a later time, in a very unpredictable and inconsistent manner, depending on which machine the code is running on?

Will assigning a pointer to (int*)malloc(0) causes unpredictable crash? How should I properly set an unused pointer?


Solution

  • Simply set it to NULL or, if your compiler supports it, to nullptr. This makes it clear that it doesn't point to anything useful.

    So either inputList=NULL or inputList=nullptr.

    Obviously, not setting it at all, is the worst thing to do. If there is any code that uses it, it will behave unpredictably.

    I'm not sure, why one would want to do inputList=(int*)malloc(0).