Search code examples
variablesundefinedc++-cliheap-memory

how to find out if a c++/cli heap variable has <undefined value>


I've not been using C++ for about 4 years and came back to it a month ago, and that was where I also have first heard about the CLI extension. I still have to get used to it, but this website helps a lot! Thank you!! Anyway, I couldn't find an answer to the following problem:

When I declare a variable

int iStack;

then it is declared but not defined, so it can have any value like

iStack = -858993460

depending on what the value at the stack position is, where the variable is created.

But when I declare a variable on the heap

int^ iHeap

then as far as I know the handle is created but the variable is not instantiated (don't know if you call it instantiation here) or defined and I can only see

iHeap = <Nicht definierter Wert>   (which means <undefined value>)

Is there any way to detect if this value is defined?

I particularly don't need it for int, but for example for

array<array<c_LocationRef^,2>^>^ arrTest2D_1D = gcnew array<array<c_LocationRef^,2>^>(2);

to find out if the elements of the outer or inner array are instantiated (I'm sure here it is an instantiation ;-) )

arrTest2D_1D = {Length=2}
   [0] = {Length=20}
   [1] = <Nicht definierter Wert>  (=<undefined value>)

Solution

  • As far as I know, the CLR automatically initialise your variables and references in C++ CLI.

    In .NET, the Common Language Runtime (CLR) expressly initializes all variables as soon as they are created. Value types are initialized to 0 and reference types are initialized to null.

    To detect if your variable is initialised, you should compare the value of your hat variable to nullptr :

    int^ iHeap;
    if(iHeap == nullptr){
        Console::WriteLine(L"iHeap not initialised");
    }
    

    This works on my VS2010 ; it outputs iHeap not initialised
    It should work for your specific problem as well (arrays).

    By the way, value types are initialised to zero hence your first example should output 0 (I've tested it, and it does output 0) :

    int iStack;
    Console::WriteLine(L"iStrack = {0}", iStack); // outputs 0
    

    Quote is from codeproject
    MSDN page for nullptr

    EDIT: Here is an other quote, from Microsoft this time :

    When you declare a handle it is automatically initialized with null, so it will not refer to anything.

    Quote from MSDN see the paragraph "Tracking Handles"