C语言,如何修复分段错误

时间:2013-03-25 02:45:15

标签: c arrays file segmentation-fault

到目前为止,这是我的代码

#define MAXROWS     60
#define MAXCOLS     60
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>


main()
{
char TableFileName[100];
char PuzzleFileName[100];
char puzzle[MAXROWS][MAXCOLS];
char line[MAXCOLS];
FILE *TableFilePtr;
int cols;
int rows;
cols=0;
rows=0;
printf("Please enter the table file name: ");
scanf("%s",TableFileName);


/* ... */

TableFilePtr = fopen(TableFileName, "r");
//printf("\n how many rows and colums are there?  separate by a space: ");
 //  scanf("%d %d",&rows, &cols);

while(fgets(line, sizeof line, TableFilePtr) != NULL)
{
    for(cols=0; cols<(strlen(line)-1); ++cols)
    {
        puzzle[rows][cols] = line[cols];
    }
    /* I'd give myself enough room in the 2d array for a NULL char in 
       the last col of every row.  You can check for it later to make sure
       you're not going out of bounds. You could also 
       printf("%s\n", puzzle[row]); to print an entire row */
    puzzle[rows][cols] = '\0';
    ++rows;
}
/*int c;
for(c=0; c<MAXROWS; ++c){
    fgets(puzzle[rows], sizeof puzzle[rows], TableFilePtr);
}*/
printf("%s",puzzle[5][5]);
}

我想做的是让它从一个文本文件中读取,该文件包含一个txt文件中的wordsearch,因此它只有随机字母。我希望能够做到这一点,以便我能够说拼图[5] [5]并且它给了我第4行和第4列中的角色。我遇到了分段错误,但我不知道如何修复它。

3 个答案:

答案 0 :(得分:2)

您正在尝试使用printf("%s", puzzle[rows][cols])打印字符串,并且char puzzle[rows][cols]是1个字符,而不是字符串。

执行此操作:printf("%c", puzzle[rows][cols]);代替。

答案 1 :(得分:0)

char puzzle[MAXROWS][MAXCOLS];
char line[MAXCOLS];
//...
while(fgets(line, sizeof line, TableFilePtr) != NULL)
{
    for(cols=0; cols<(strlen(line)-1); ++cols)
    {
        puzzle[rows][cols] = line[cols];
    }
    puzzle[rows][cols] = '\0';
    ++rows;
}

这很危险,因为您从不检查行数是否小于MAXROWS,或者每行的长度是否小于MAXCOLS。这意味着格式错误的数据文件可能导致您超出puzzle数组的边界进行写入,这可能导致分段错误,内存损坏或其他问题。

要修复,您需要在循环条件中包含限制,如下所示:

while (frets(line, sizeof line, TableFilePtr) != NULL && rows < MAXROWS) {
    for (cols=0; cols<(strlen(line)-1) && cols < MAXCOLS; ++cols) {
        //...

答案 2 :(得分:0)

我没有看到明显的错误,除了你在写字符时没有检查拼图数组的边界。所以我想也许一个可能的原因是你的输入文件太大而无法放入拼图数组,那么数组已经溢出。