如果使用相同的阵列作为这两个参数的strcat()崩溃 [英] strcat() crashes if using same array as both parameters

查看:219
本文介绍了如果使用相同的阵列作为这两个参数的strcat()崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char r[40];
strcpy(r,"abcdef");
strcat(r,r);

我的程序崩溃在第三行?

My program crashes at the third line?

更换的strcat(R,R);由strcat的(R,ABCDEF);工作正常,虽然....这是为什么?

Replacing strcat(r,r); by strcat(r,"abcdef"); works fine though.... why is that?

推荐答案

的strcat()从输入,并将其复制到输出读取直到它找到一个 \\ 0 终止输入。通过指定的输入和输出在同一个阵列,正在修改的输入,同时它被读出。

strcat() reads from the input and copies it to the output until it find a \0 terminator in the input. By specifying the same array for both input and output, you are modifying the input while it is being read from.

您必须检查你的编译器的特定实现中的strcat(),但如果你跟踪通过一个简单的执行类似以下,你应该明白为什么你的$ C $一段时间后死机ç:

You would have to check your compiler's particular implementation of strcat(), but if you trace through a simple implementation like the following, you should see why your code crashes after awhile:

char *strcat(char *dest, const char *src )
{
    char *ret = dest;
    if (dest && src)
    {
        while (*dest != 0)
            ++dest;
        while (*str != 0)
            *dest++ = *src++;
        *dest = 0;
    }
    return ret;
}

而(* DEST!= 0)循环, DEST 现在指向在输入的 \\ 0 终止。的第一次迭代而(*海峡!= 0)循环再替换终止与 A ,从而导致循环不再把车子停在它应该。最终,循环将超过输入的范围,并开始阅读周围的内存,并最终如果没有找到它将会崩溃另一个 \\ 0 字节击中无效的内存了。

After the while (*dest != 0) loop, dest is now pointing at the input's \0 terminator. The first iteration of the while (*str != 0) loop then replaces that terminator with a, thus causing the loop to no longer stop where it is supposed to. Eventually, the loop will exceed the bounds of the input and start reading surrounding memory, and eventually it will crash if it does not find another \0 byte before hitting invalid memory.

这篇关于如果使用相同的阵列作为这两个参数的strcat()崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆