c - 在动态数组上使用 strcpy

标签 c arrays string pointers strcpy

我有一个关于以下代码的基本问题:

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 by s2 (including the terminating null character) into the array pointed to by s1. [...]

然后,对于“字符串函数约定”,§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/

相关文章:

c++ - C 源代码分词器

c - C 中的 "str"- "str"如何工作?它们是如何存储的?

javascript - 数组大小的实际限制

arrays - 对两个数组进行排序所需的最小 "swaps"数

arrays - Swift4 initWithArray 等价物

Pandas :将对象转换为 str

Python 字符串比较似乎不起作用

c++ - 是否可以在C/C++中的for循环的增量部分进行多次操作?

c - 在C中将2个ascii字符存储到1个整数中

c - 在 x86 汇编中,为什么读取标准输入会阻塞程序?