所以我读到要谨慎使用 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通过写入缓冲区的末尾。这就是第二段代码中发生的事情。
第一段代码也是无效的,因为src
和dest
都是未初始化的指针。当您将它们传递给 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/