C:为什么会出现细分错误?

时间:2019-09-30 12:00:43

标签: c segmentation-fault

基本上我正在尝试打印类似 “ 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; 
}

2 个答案:

答案 0 :(得分:3)

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

  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)

您的代码中有两个问题
1.由于您的 count 变量。您不会递增count变量,因此count始终为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;

}