Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ strcpy System.AccessViolationException异常_C++_C++ Cli - Fatal编程技术网

C++ strcpy System.AccessViolationException异常

C++ strcpy System.AccessViolationException异常,c++,c++-cli,C++,C++ Cli,当我到达strcpy线时,我会 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 =

当我到达strcpy线时,我会

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));

您需要分配内存并将
指向该内存。现在,
out
指向某个随机内存位置。

在设置str之后,但在将其复制到out之前:

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

if (out != NULL) {
    strcpy(out, str);
}
因为您需要某种类型的缓冲区来进行复制。完成后一定要释放出来。


“方法3”看起来非常简单。无需手动释放内存

分配的内存长度应该是多少?长度应该是
(strlen(str)+1)*sizeof(char)
sizeof(char)==1platform@qehgt是的,如果OP好奇的话,我只是想明确地说明我在做什么。malloc的第行显示错误C2440:“初始化”:无法从“void*”转换为“char*”@bestnagi-Ah,你需要转换它。通常,我会从mallocs显式地编写强制类型转换,但最近我有理由不这样做。我得重新考虑一下,呵呵。