Jeff Goes Jeff Goes - 1 month ago 14
C Question

Segmentation Fault: 11 while Reading File

I don't know why but I am not being able to read a

txt
file and I have been receiving a Segmentation Fault 11 error and I'm not sure why. I have to read a maze that was written previously on a txt file. Apparently everything looks fine for me. Does anyone see anything wrong?

I appreciate it a lot.

enum directions {DIR_UP, DIR_DOWN, DIR_LEFT, DIR_RIGHT};

typedef struct {
int y, x;
enum directions d;

int lins, cols;
char **maze;
} t_maze;



t_maze *read_maze (char *file) {

FILE *f = fopen (file, "r");

if (!f) {
return NULL;
}

t_maze *my_maze = (t_maze *) malloc (sizeof (t_maze));
fscanf (f, "%d %d %d %d\n", &(my_maze->lins), &(my_maze->cols), &(my_maze->x), &(my_maze->y));


int lin;
my_maze->maze = (char **) malloc (my_maze->lins * sizeof (char *));
for (lin = 0; lin < my_maze->lins; lin++) {
my_maze->maze[lin] = (char *) malloc ((my_maze->cols) * sizeof (char));
}


lin = 0;
while (!feof (f)) {
int read, col = 0;
do {
read = getc (f);

if (read != '\n') {
my_maze->maze[lin][col++] = read;
}
} while (read != '\n');
lin++;
}

fclose (f);
return my_maze;
}

int main (int argc, char *argv[]) {
if (argc > 1) {

t_maze *m = read_maze (argv[1]);

return 0;
}

Answer

You can add ferror() after getc to check for reading error. You need to check that read != EOF also. Also, you have to check for lin and col.

 lin = 0;
 while (!feof (f) && lin < my_maze->lins) {
   int read, col = 0;
   do {
        read = getc (f);

        if (ferror(f)) {
            perror();
            exit 0;
        }

        if (read != '\n') {
            my_maze->maze[lin][col++] = read;
        }

    } while (read != '\n' && read != EOF && col < my_maze->cols);
    lin++;
 }
Comments