【发布时间】:2018-04-24 10:00:35
【问题描述】:
我正在尝试让我的代码从内容涉及的文本文件中读取: (文本文件名为maze1.txt)
5 5
%%%%%
S % %
% % %
% E
%%%%%
但是,每当我尝试运行程序时,我都会收到 分段错误,我认为这与我使用 malloc 的方式有关。我知道我已经使用第一个数字来为我的数组设置边界,但我不确定如何做到这一点。
提供的是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include "maze.h"
maze_t * createMaze(char * fileName)
{
typedef struct Maze{
int cols, rows;
char **charRow;
}MAZE;
struct Maze maze;
FILE *pf;
int i,j,k;
pf = fopen(fileName,"r");
k = fscanf(pf, "%i %*c %i", &maze.cols, &maze.rows);
char cMaze[maze.cols][maze.rows];
int new;
int *newMaze = (int *)malloc( maze.rows * maze.cols * sizeof(int));
for(i = 0; maze.rows; i++){
for(j = 0; j < maze.cols; j++){
cMaze[i][j] = fgetc(pf);
putchar( cMaze[i][j] );
}
}
printf("%d", cMaze[maze.cols][maze.rows]);
printf("\n");
maze.charRow = newMaze;
fclose(pf);
return newMaze;
}
这是我的主要内容:
#include <stdio.h>
#include "maze.h"
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("You need a valid input maze file.\n");
return -1;
}
printf("Creating maze with file %s\n", argv[1]);
maze_t * maze = createMaze(argv[1]);
printf("\nUnsolved maze:\n");
printMaze(maze);
if(solveMazeManhattanDFS(maze, maze->startColumn, maze->startRow))
{
printf("\nSolved maze:\n");
printMaze(maze);
if(checkMaze(maze))
{
printf("Solution to maze is valid\n");
}
else
{
printf("Incorrect solution to maze\n");
}
}
else
{
printf("\nMaze is unsolvable\n");
}
printf("\nDestroying maze\n");
destroyMaze(maze);
return 0;
}
结构体maze_t的定义是
typedef struct {
int width;
int height;
int startColumn;
int startRow;
int endColumn;
int endRow;
char ** cells;
} maze_t;
【问题讨论】:
-
检查fscanf的返回值。检查malloc的返回值。
-
并使用调试器。
-
并检查
fopen的返回值。 -
一方面
fscanf格式错误,它应该是%i%i或者更确切地说是%d%d。%*c和后面的 ` ` 不能匹配任何东西,因此另一个维度是垃圾,您可以用完内存,或者分配 0 个字节,然后针对 NULL 指针运行。但我的水晶球对此有点模糊。 -
要生成一个实际的minimal reproducible example,您应该添加
#includes 和一个main函数!
标签: c file segmentation-fault malloc maze