2012-07-24 50 views
0

當我到了strcpy的線,我得到的strcpy System.AccessViolationException

An unhandled exception of type 'System.AccessViolationException' occurred. 
Additional information: Attempted to read or write protected memory. 
This is often an indication that other memory is corrupt. 


char* str; char* out; 
str = (char*) Marshal::StringToHGlobalAnsi(Parms["AVI"]).ToPointer(); 
strcpy(out, str); 
Marshal::FreeHGlobal(IntPtr(str)); 

回答

2

您需要分配內存和點out到內存中。現在,out指向一些隨機存儲位置。

+0

分配內存的長度應該是多少? – fmvpsenior 2012-07-24 17:57:50

+0

長度應該是'(strlen(str)+ 1)* sizeof(char)'。 – tumdum 2012-07-24 18:04:02

+0

是的,感謝捕捉,:) – AlcoJaguar 2012-07-24 18:13:51

0

在設置海峽,但你把它複製到之前:

char* out = (char*)malloc((strlen(str) + 1) * sizeof(char)); 

if (out != NULL) { 
    strcpy(out, str); 
} 

當你需要某種緩衝區複製到的。一定要在完成時釋放(外出)。

+0

'sizeof(char)== 1'在*每個*平臺 – qehgt 2012-07-24 18:01:43

+0

@qehgt是的,只是試圖明確和清楚我在做什麼,如果OP很好奇。 – AlcoJaguar 2012-07-24 18:04:30

+0

malloc行說錯誤C2440:'初始化':不能從'void *'轉換爲'char *' – fmvpsenior 2012-07-24 18:07:39