2010-11-27 73 views
0

我是.Net的新手,並試圖使用託管線程。 我在代碼中找不到任何問題,但它在線程結束時觸發異常。 類似於: 未處理的異常0x5cbf80ea(msvcr90d.dll) 0xC0000005:訪問衝突讀取位置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; 
} 

但是,當我將緩衝區分配爲全局數組時,它工作正常。當我使用「new」關鍵字時,這個異常就開始了,因此是一個動態的內存分配。 我在做任何根本性的錯誤? 這是處理垃圾收集器的東西嗎?或由「新」關鍵字分配的非託管堆? 我真的希望有這個緩衝區在非託管堆。儘管我正在編寫託管代碼,但我正在使用的許多其他DLL都是非託管的。

回答

2
dt = new int(sz); 

這被分配單個整數,(數組),並用sz(100)的值進行初始化。你想要的是這樣的:

dt = new int[sz]; 

此分配大小dt陣列。請注意,爲避免內存泄漏,您必須稍後將其釋放:

delete [] dt; 
+0

非常感謝。這確實是一個基本的錯誤。 直到線程嘗試結束,調試器纔會報錯。 VS調試器不知道這種情況?我很驚訝,調試器沒有處理好。 – Anniffer 2010-11-29 12:57:17

相關問題