简体   繁体   English

在动态数组上使用strcpy

[英]Using strcpy on a dynamic array

I have got a basic question about the following code: 我对以下代码有一个基本问题:

int main() {
    char *sNext1="DABCD";
    char Tmp[]="";
    strcpy(Tmp, sNext1);
    return 0;
}

There is a error happened in "strcpy" when I run it. 运行“ strcpy”时发生错误。 It seems that it doesn't allow me to copy a string into a dynamic array. 似乎不允许我将字符串复制到动态数组中。 Does anyone know what causes this error? 有人知道导致此错误的原因吗? And how can I fix it? 我该如何解决?

The problem here is with 这里的问题是

 char Tmp[]="";

here, Tmp is not an dynamic array, it's an array with exactly one element (initialized via the initializer). 在这里, Tmp 不是动态数组,它是一个只有一个元素的数组(通过初始化程序初始化)。 When you use this as destination for strcpy() , you're overrunning the buffer. 当您将其用作strcpy()目标时,您正在溢出缓冲区。 Basically, your code tries to access out of bound memory, which invokes undefined behavior . 基本上,您的代码尝试访问超出范围的内存,这会调用未定义的行为

Related, quoting C11 , chapter §7.24.2.3, strcpy() , emphasis mine 相关内容,引用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 . strcpy函数将s2指向的字符串(包括终止空字符)复制到s1指向的数组中。 [...] [...]

and then, for "String function conventions", §7.24.1, 然后,对于“字符串函数约定”,第7.24.1节,

[....] If an array is accessed beyond the end of an object, the behavior is undefined. [....]如果在对象末尾之外访问数组,则行为未定义。

Solution : You need to ensure that Tmp has enough memory to hold the content to be copied into it, including the null terminator. 解决方案 :您需要确保Tmp有足够的内存来保存要复制到其中的内容,包括空终止符。

That said, for a hosted environment, int main() should at least be int main(void) to be conforming to the standard. 也就是说,对于托管环境, int main()至少应为int main(void)以符合标准。

Allocate memory to Tmp before copying the string to Tmp . 在将字符串复制到Tmp之前,先将内存分配给Tmp

Tmp is an character array of size 1. Tmp是大小为1的字符数组。

Allocate memory dynamically as shown below. 如下所示动态分配内存。 (If you are trying to do dynamic memory allocatio) (如果您尝试进行动态内存分配)

char *Tmp = malloc(strlen(sNext1) + 1);

Then try doing strcpy() 然后尝试做strcpy()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM