multithreadingheap-memoryunmanagedmanagedheap-corruption

Passing unmanaged array to a Managed Thread. - memory corruption


I'm a newbie for .Net and trying to use managed threading. I couldn't find any problem in my code, but it triggers an exception when the Thread Ends. Something like: Unhandled exception at 0x5cbf80ea (msvcr90d.dll) 0xC0000005: Access violation reading location 0x000000d7.

#include "stdafx.h"

using namespace System;
using namespace System::Threading;

#define sz 100

//int dt[sz]; //allcating a gloal buffer
int *dt;


void workerThread (void)
{
    Console::WriteLine("Producer Thread Started!");
    int data = 50;
    for(int i=0; i<sz; i++)
    {
        Thread::Sleep(1);
        dt[i] = i;
        Console::WriteLine("Producer W={0}", i);
    };
    Console::WriteLine("Producer Thread Ending");
}

int main(array<System::String ^> ^args)
{
    Console::WriteLine("This is a test on global variable and threading");
    //allcating a buffer
    dt = new int(sz);

    Thread ^wthrd = gcnew Thread(gcnew ThreadStart(&workerThread));
    //Starting Worker Thread..
    wthrd->Start(); 
    //Waiting for Worker Thread to end.
    wthrd->Join();  
    Console::WriteLine("Worker Thread Ended.");
    Console::ReadKey();
    return 0;
}

However it works fine when I allocate the buffer as a global array. This exception kicks in when I use "new" keyword, hence a dynamic memory allocation. Am I making any fundamental mistakes? Is this something to deal with the garbage collector? or Unmanaged heap allocated by the "new" keyword? I would really prefer to have this buffer in unmanaged heap. Although I am writing a managed code, many other DLLs I am using are unmanaged.


Solution

  • dt = new int(sz);
    

    This is allocating a single integer, (not an array), and initializing it with the value of sz (100). What you want is this:

    dt = new int[sz];
    

    This allocates an array of size dt. Note that in order to avoid leaking memory, you must later free it like this:

    delete [] dt;