使用 strcat(num, num) 将字符串连接到自身时出现分段错误
Segmentation fault while using strcat(num, num) to concatenate string to itself
我使用 strcat 函数连接“1”和“1”,结果是“11”,但出现分段错误。
我的代码如下:
#include <stdio.h>
#include <string.h>
int main(){
char num[10] = "1";
strcat(num, num);
printf("%s", num);
}
考虑到最有可能实现strcat
,请不要这样做。通常,为输入和输出传递相同参数的函数是一个坏主意。事实上,让我们把它说得好一点。除非函数说它已定义,否则它没有定义,所以不要这样做。
试试这个:
size_t n = strlen(num);
memmove(num + n, num, n + 1);
memmove
是一个很好的函数,专为重叠输入和输出而设计。
您不能使用 strcat
连接两个重叠的字符串,包括它们是相同字符串的情况。
https://en.cppreference.com/w/c/string/byte/strcat:“如果字符串重叠则行为未定义。”
C17 7.24.3.1 (2): "如果复制发生在重叠的对象之间,行为是
未定义。
您必须手动编写连接例程,或者考虑基于 memcpy
的解决方案。
您需要两个 char[],一个作为源,另一个作为目标,目标数组必须初始化并且有足够的 space 来容纳源长度。
#define DEST_SIZE 40
int main(){
char num[10] = "1";
char dest[DEST_SIZE] = "1"; //Destination with null characters after "1"
strcat(dest,num);
printf(dest);
return 0;
}
关于不同场景的详细解释:here
我使用 strcat 函数连接“1”和“1”,结果是“11”,但出现分段错误。
我的代码如下:
#include <stdio.h>
#include <string.h>
int main(){
char num[10] = "1";
strcat(num, num);
printf("%s", num);
}
考虑到最有可能实现strcat
,请不要这样做。通常,为输入和输出传递相同参数的函数是一个坏主意。事实上,让我们把它说得好一点。除非函数说它已定义,否则它没有定义,所以不要这样做。
试试这个:
size_t n = strlen(num);
memmove(num + n, num, n + 1);
memmove
是一个很好的函数,专为重叠输入和输出而设计。
您不能使用 strcat
连接两个重叠的字符串,包括它们是相同字符串的情况。
https://en.cppreference.com/w/c/string/byte/strcat:“如果字符串重叠则行为未定义。”
C17 7.24.3.1 (2): "如果复制发生在重叠的对象之间,行为是 未定义。
您必须手动编写连接例程,或者考虑基于 memcpy
的解决方案。
您需要两个 char[],一个作为源,另一个作为目标,目标数组必须初始化并且有足够的 space 来容纳源长度。
#define DEST_SIZE 40
int main(){
char num[10] = "1";
char dest[DEST_SIZE] = "1"; //Destination with null characters after "1"
strcat(dest,num);
printf(dest);
return 0;
}
关于不同场景的详细解释:here