[英]Supply a string that is not null terminated to strcpy
Here is the code 这是代码
smem_dmp(char *name, char content[])
{
int i;
int len = strlen(content);
printf("%s\n\n", name);
for(i = 0; i < len; i++)
{
printf("%c\t%p\n", content[i], &content[i] );
}
printf("Done\n\n");
}
print_bar()
{
printf("********************************************************************\n");
}
int main(int argc, char *argv[])
{
char a[16];
char b[16];
strcpy(a, "abcdefghijklmnop");
printf("a = %s\nb = %s\n\n",a,b);
smem_dmp("A", a);
smem_dmp("B", b);
print_bar();
strcpy(b, "ABCDEFGHILKLMNOP");
printf("a = %s\nb = %s\n\n",a,b);
smem_dmp("A", a);
smem_dmp("B", b);
system("PAUSE");
return 0;
}
From looking at where a and b reside in memory I have worked out what is happening. 从查看a和b驻留在内存中的位置,我已经找到了正在发生的事情。 The string copied to b is not null terminated. 复制到b的字符串不是以null结尾。 This is causing the contents of a to be removed because b is located (0028FF20) before a in memory (0028FF30). 这导致a的内容被移除,因为b位于存储器(0028FF30)之前(0028FF20)。
What is happening? 怎么了? Does strcpy(b,"string") not stop until it has gone through all the memory on the stack frame variables? strcpy(b,“string”)是否在经过堆栈帧变量的所有内存之前不会停止? Sorry if I am not using the correct terminology. 对不起,如果我没有使用正确的术语。 :) :)
What is happening? 怎么了? Does
strcpy(b,"string")
not stop until it has gone through all the memory on the stack frame variables?strcpy(b,"string")
是否在经过堆栈帧变量的所有内存之前不会停止?
strcpy
copies bytes until it finds a 0-byte in the source. strcpy
复制字节,直到它在源中找到0字节。 That is copied to the destination, and then strcpy
returns. 将其复制到目标,然后strcpy
返回。 (If the destination isn't big enough to hold the source including the 0-terminator, the behaviour is undefined, but unless you get a segmentation fault, that is what in practice you can rely on happening.) (如果目标不足以容纳包含0终结符的源,则行为未定义,但除非您遇到分段错误,否则实际上您可以依赖于此。)
So 所以
strcpy(b, "ABCDEFGHILKLMNOP");
copies 17 bytes - the 16 letters and the 0-terminator - from the string literal to the array b
, which only contains 16 elements. 将17个字节(16个字母和0个终止符)从字符串文字复制到数组b
,后者只包含16个元素。 That means the 0-terminator is written one element past the end of the array b
. 这意味着0-terminator被写入超过数组b
末尾的一个元素。 In your situation, that is the first byte in a
, and the strcpy(b, "ABCDEFGHIJKLMNOP");
在你的情况,那就是在第一个字节a
,和strcpy(b, "ABCDEFGHIJKLMNOP");
effectively makes a
contain an empty string. 有效地使a
包含空字符串。
"abcdefghijklmnop"
的大小是16,你a
数组的大小是16,它应该是17(16 + 1 null终结符charachter)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.