简体   繁体   English

将字符串与自身连接两次会导致分段错误

[英]Concatenating string with itself two times give segmentation fault

#include <stdio.h>

int main(void)
{
    char a[100] = "hi";

    strcat(a, a);
    strcat(a, a);

    printf("%s\n", a);

    return 0;
}

From the definition of strcat in the C language standard, §7.21.3.1/2来自C语言标准中strcat的定义, §7.21.3.1/2

If copying takes place between objects that overlap, the behavior is undefined.

My compiler crashes even when it's done once, as strcat(a, a);我的编译器即使完成一次也会崩溃,如strcat(a, a); copies the first character of the second argument over the '\\0' at the end of the first argument, then the second character of the second argument after it, etc until it encounters a '\\0' in the second argument.. which never happens because that '\\0' was gone when the first character was copied.将第二个参数的第一个字符复制到第一个参数末尾的 '\\0' 上,然后复制第二个参数的第二个字符,依此类推,直到它在第二个参数中遇到 '\\0' ......发生的原因是复制第一个字符时 '\\0' 消失了。

From strcat(3) manpage:从 strcat(3) 联机帮助页:

DESCRIPTION

The strcat() and strncat() functions append a copy of the null-terminated
string s2 to the end of the null-terminated string s1, then add a termi-
nating '\\0'. The string s1 must have sufficient space to hold the
result.

The strncat() function appends not more than n characters from s2, and
then adds a terminating \\0'.` then adds a terminating \\0'。`

The source and destination strings should not overlap, as the behavior is
undefined.

This is undefined behavior.这是未定义的行为。

If you're in a loop, reading each char from a string, until \\0 is found, but at the same time you're appending (writing) chars to the end of it, when is the loop going to end?如果您在循环中,从字符串中读取每个char ,直到找到\\0 ,但同时您将(写入)字符附加到它的末尾,那么循环何时结束?

I suspect it's because the implementation is overwriting the null byte at the end:我怀疑这是因为实现在最后覆盖了空字节:

Start: a = {h,i,\0}
         src^   vdst
next:  a = {h,i,h}
           src^   vdst
next:  a = {h,i,h,i}
             src^   vdst
next:  a = {h,i,h,i,h}
...

Because you overwrote the null terminator, your source string will never end and the method will keep copying until it tries to access memory it shouldn't and segfaults.因为您覆盖了空终止符,所以您的源字符串将永远不会结束,并且该方法将继续复制,直到它尝试访问它不应该访问的内存和段错误。

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

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