c - Loop后输出错误是strcat引起的?

标签 c loops 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 是:nameoppsoppsopps

我的问题是“为什么 printf 循环 1886416641 次?”此外,结果也不是我所期望的。有人可以为我澄清一下吗?

最佳答案

str1 只分配了 5 个字节,strcat 将越界访问,这可能会导致未定义的行为。

号码 1886416641 只是不小心得到的。

您必须为 str1 分配足够的内存才能获得正常结果。
示例:char src1[32] = "name";

关于c - Loop后输出错误是strcat引起的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32934891/

相关文章:

c++ - Contiki 中的内存溢出

c - 如何将十六进制转换为二进制

C: pthread 段错误

编译时的 C 函数装饰器(包装器)

python - 使用 Python 解析 JSON 文件中的字典

ios - 如何在sqlite中使用循环从特定列获取名称

c - 向 C 中的 const 数组添加新元素

loops - 在emu8086中打印从1到<用户输入

c - 使用 strcat 向 char** 元素添加空格

c - 如何使用 strcat() 函数?