我有一个关于以下代码的基本问题:
int main() {
char *sNext1="DABCD";
char Tmp[]="";
strcpy(Tmp, sNext1);
return 0;
}
运行“strcpy”时出现错误。似乎它不允许我将字符串复制到动态数组中。有谁知道导致此错误的原因?我该如何解决?
最佳答案
这里的问题是
char Tmp[]="";
这里,Tmp
不是动态数组,它是一个恰好只有一个元素的数组(通过初始化器初始化)。当您将其用作 strcpy()
的目标时,您将溢出缓冲区。基本上,您的代码会尝试访问超出限制的内存,这会调用 undefined behavior .
相关,引用 C11
,章节 §7.24.2.3,strcpy()
,强调我的
The
strcpy
function copies the string pointed to bys2
(including the terminating null character) into the array pointed to bys1
. [...]
然后,对于“字符串函数约定”,§7.24.1,
[....] If an array is accessed beyond the end of an object, the behavior is undefined.
解决方案:您需要确保Tmp
有足够的内存容纳要复制到其中的内容,包括空终止符。
也就是说,对于托管环境,int main()
至少应该是 int main(void)
才能符合标准。
关于c - 在动态数组上使用 strcpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40256559/