C:为什么会出现这种分段错误?



基本上我正在尝试打印类似的东西 "1 2 3"

但是,当我在终端上运行它时,它会在没有任何解释的情况下给我分段错误......

#include <stdio.h>
#include <string.h>
int main() {
int width = 4;
char complete_row[width * 3 * 2];
char one[3], two[3], three[3], space[1];
strcpy(space, " ");
strcpy(complete_row, "");
int count = 0;
//make sure single line of color is replicated as much as width
while (count < width) {
strcpy(one, "1");
strcat(one, space);
strcpy(two, "2");
strcat(two, space);
strcpy(three, "3");
strcat(complete_row, one);
strcat(complete_row, two);
strcat(complete_row, three);
}
//print that twice in the output file
printf("%s", complete_row);
printf("%s", complete_row);
return 0; 
}

代码中至少存在两个问题:

  1. while 循环永远不会停止,因为您不会在循环中递增count。因此,您将字符串连接起来一遍又一遍地complete_row,最终导致缓冲区溢出,从而导致未定义的行为(可能是段错误(
  2. char space[1]声明一个只能容纳一个字符的数组,但对于" ",由于 NUL 字符串终止符,您需要两个字符。越界访问数组会导致未定义的行为(可能是段错误(。

更正代码,见注释(未经测试,可能会有更多问题(

int main() {
int width = 4;
char complete_row[width * 3 * 2];
char one[3], two[3], three[3], space[2];  // space[2]
strcpy(space, " ");
strcpy(complete_row, "");
int count = 0;
//make sure single line of color is replicated as much as width
while (count < width) {
strcpy(one, "1");
strcat(one, space);
strcpy(two, "2");
strcat(two, space);
strcpy(three, "3");
strcat(complete_row, one);
strcat(complete_row, two);
strcat(complete_row, three);
count++;    // increment count
}
//print that twice in the output file
printf("%s", complete_row);
printf("%s", complete_row);
return 0; 
}

代码中有两个问题
1.因为你的计数变量。您没有递增计数变量,因此计数始终为 0,而循环永远不会结束或无限。
2.空间阵列的大小不够。

此外,对于预期的结果,您在编写串联代码时不必在此处应用循环。因此,删除循环将起作用。粘贴您的工作代码。

#include <stdio.h>
#include <string.h>
int main() {
int width = 4;
char complete_row[width * 3 * 2*2];
char one[3], two[3], three[3], space[1];
strcpy(space, " ");
strcpy(complete_row, "");
int count = 0;
//make sure single line of color is replicated as much as width
strcpy(one, "1");
strcat(one, space);
strcpy(two, "2");
strcat(two, space);
strcpy(three, "3");
strcat(complete_row, one);
strcat(complete_row, two);
strcat(complete_row, three);
//print that twice in the output file
printf("%s", complete_row);
return 0;

}

相关内容

  • 没有找到相关文章

最新更新