"strcat function in C assumes the destination string is large enough to hold contents of source string and its own."困惑

标签 c string strcat

所以我读到要谨慎使用 strcat 函数,因为目标字符串应该足够大以容纳其自身和源字符串的内容。我编写的以下程序也是如此:

#include <stdio.h>
#include <string.h>

int main(){
    char *src, *dest;
    printf("Enter Source String : ");
    fgets(src, 10, stdin);
    printf("Enter destination String : ");
    fgets(dest, 20, stdin);
    strcat(dest, src);
    printf("Concatenated string is %s", dest);
    return 0;
}

但我在这里写的不是这样:

#include <stdio.h>
#include <string.h>

int main(){
    char src[11] = "Hello ABC";
    char dest[15] = "Hello DEFGIJK";
    strcat(dest, src);
    printf("concatenated string %s", dest);
    getchar();
    return 0;
}

该程序最终将两者相加,但没有考虑到目标字符串不够大。为什么会这样?

最佳答案

strcat 函数无法知道目标缓冲区的确切长度,因此它假定传递给它的缓冲区足够大。如果不是,则调用 undefined behavior通过写入缓冲区的末尾。这就是第二段代码中发生的事情。

第一段代码也是无效的,因为srcdest都是未初始化的指针。当您将它们传递给 fgets 时,它会读取它们包含的任何垃圾值,将其视为有效地址,然后尝试将值写入该无效地址。这也是未定义的行为。

使 C 语言快速的原因之一是它不会检查以确保您遵守规则。它只是告诉你规则并假设你遵守它们,如果你不遵守,坏事可能会发生也可能不会发生。在您的特定情况下,它似乎有效,但不能保证。

例如,当我运行您的第二段代码时,它似乎也能正常工作。但是如果我把它改成这样:

#include <stdio.h>
#include <string.h>

int main(){
    char dest[15] = "Hello DEFGIJK";
    strcat(dest, "Hello ABC XXXXXXXXXX");
    printf("concatenated string %s", dest);
    return 0;
}

程序崩溃。

关于 "strcat function in C assumes the destination string is large enough to hold contents of source string and its own."困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51860543/

相关文章:

python - 为什么 re.Match 对象返回的结束索引高于预期?

c - strcat 和段错误 11

c - C 中的 strcat() 和 fgets() 不起作用

string - Excel VBA 对大型文档进行字符串操作导致运行时错误 "1004"

c - 如何修改字符串拆分函数以忽略连续的分隔符?

c++ - 字的字节返回比它应该的少一

c - 为什么我的 popen 失败

c++ - Z3:创建具有动态已知项数的枚举类型

c - 如果字符串中间出现空字符怎么办?

java - Linux/X Window 系统下的屏幕阅读/鼠标点击?