Loop后输出错误是strcat引起的?
Error in output after Loop is caused by strcat?
我有以下代码在循环中将字符串附加到另一个字符串。
代码
#include<stdio.h>
#include<string.h>
int main(void){
char src1[] = "name";
int i;
for (i=1;i<=5;i++){
strcat(src1,"opps");
printf("loop times %d\n",i);
}
printf("now src1 is:%s\n",src1);
return 0;
}
为了调试代码,我在代码中添加了 printf
语句并编译了它。当我 运行 时,我得到以下结果:
输出
循环次数1
循环次数 0
循环时间 1886416641
现在 src1 is:nameoppsoppsopps
我的问题是 "Why does printf
loop 1886416641 times?" 另外,结果也不是我所期望的。有人可以为我澄清一下吗?
只有5个字节分配给str1
,strcat
将越界访问,然后可能会导致未定义的行为。
号码1886416641
是不小心得到的
您必须为 str1
分配足够的内存才能获得正常结果。
示例:char src1[32] = "name";
您的 src1[]
不够大。当您追加第二个 "opps" 时,它会覆盖 i
。值 1886416641 为十六进制 70706f01:0x70= 'p'、0x70= 'p'、0x6f= 'o'.
编译器已舍入到下一个 32 位机器字。以字节为单位的堆栈如下所示:
start: loop1 loop2
src1[]:
n
a
m
e
[=10=] o
<fill> p
<fill> p
<fill> s
i:
00 [=10=] o
00 00 p
00 00 p
01 02 s
[=10=]
(堆叠不准确;有些元素实际上是颠倒的——以它为例)
根据 strcat()
、
的 man page,为现有答案添加一些细节
char *strcat(char *dest, const char *src);
The strcat()
function appends the src
string to the dest
string, overwriting the terminating null byte ('[=20=]') at the end of dest
, and then adds a terminating null byte. The strings may not overlap, **and the dest
string must have enough space for the result. If dest
is not large enough, program behavior is unpredictable; [...]
万一您的最终字符串的长度超过目标可以存储的长度,您将访问超出限制的内存,这会导致 undefined behavior。
在您的代码中,src1
从初始化字符串的长度获取其大小。后面一点,如果要存储更长的,就需要在开始的时候分配更多的存储空间,比如
char src1[128] = "name";
或类似。
我有以下代码在循环中将字符串附加到另一个字符串。
代码
#include<stdio.h>
#include<string.h>
int main(void){
char src1[] = "name";
int i;
for (i=1;i<=5;i++){
strcat(src1,"opps");
printf("loop times %d\n",i);
}
printf("now src1 is:%s\n",src1);
return 0;
}
为了调试代码,我在代码中添加了 printf
语句并编译了它。当我 运行 时,我得到以下结果:
输出
循环次数1 循环次数 0 循环时间 1886416641 现在 src1 is:nameoppsoppsopps
我的问题是 "Why does printf
loop 1886416641 times?" 另外,结果也不是我所期望的。有人可以为我澄清一下吗?
只有5个字节分配给str1
,strcat
将越界访问,然后可能会导致未定义的行为。
号码1886416641
是不小心得到的
您必须为 str1
分配足够的内存才能获得正常结果。
示例:char src1[32] = "name";
您的 src1[]
不够大。当您追加第二个 "opps" 时,它会覆盖 i
。值 1886416641 为十六进制 70706f01:0x70= 'p'、0x70= 'p'、0x6f= 'o'.
编译器已舍入到下一个 32 位机器字。以字节为单位的堆栈如下所示:
start: loop1 loop2
src1[]:
n
a
m
e
[=10=] o
<fill> p
<fill> p
<fill> s
i:
00 [=10=] o
00 00 p
00 00 p
01 02 s
[=10=]
(堆叠不准确;有些元素实际上是颠倒的——以它为例)
根据 strcat()
、
char *strcat(char *dest, const char *src);
The
strcat()
function appends thesrc
string to thedest
string, overwriting the terminating null byte ('[=20=]') at the end ofdest
, and then adds a terminating null byte. The strings may not overlap, **and thedest
string must have enough space for the result. Ifdest
is not large enough, program behavior is unpredictable; [...]
万一您的最终字符串的长度超过目标可以存储的长度,您将访问超出限制的内存,这会导致 undefined behavior。
在您的代码中,src1
从初始化字符串的长度获取其大小。后面一点,如果要存储更长的,就需要在开始的时候分配更多的存储空间,比如
char src1[128] = "name";
或类似。