Hie there, when executing the following code, I get “*** stack smashing detected ***: terminated Aborted (core dumped)”. I’m using using gcc version ((Ubuntu 8.2.0-7ubuntu1) 8.2.0)
my main file contains the following code
//Header Files
#include <stdio.h>
#include <stdlib.h>
char** maze; //Stores maze characters as a 2D array
int** visited;
int rows;
int cols;
int start_row;
int start_col;
enum enviro_terrain{
empty,
wall,
goal,
crumb
};
void alloc_maze(){
maze = malloc(rows * sizeof(char*));
for (int i = 0; i < rows; i++){
maze[i] = malloc(cols * sizeof(char*));
}
}
void alloc_visited(){
visited = malloc(rows * sizeof(char*));
for (int i = 0; i < rows; i++){
visited[i] = malloc(cols * sizeof(char*));
}
}
void get_maze(char* file_name){
char c;
char rows_s[3] = {'\0'}; //'\0'-String terminator
char cols_s[3] = {'\0'};
int rows_i = 0; //get the row number
int cols_i = 0; //get the column number
int swap = 0;
FILE* file = fopen(file_name, "r");
if (file){
while((c = getc(file) != EOF)){
if (c == '\n'){
break;
}else if (c == ','){
swap = 1;
}else if (!swap){
rows_s[rows_i] = c;
rows_i++;
}else {
cols_s[cols_i] = c;
cols_i++;
}
}
}
rows = atoi(rows_s);
cols = atoi(cols_s);
alloc_maze();
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
c = getc(file);
if (c == '\n'){
c = getc(file);
}
maze[i][j] = c;
if (c == 's'){
start_row = i;
start_col = j;
}
}
}
fclose(file);
}
void get_visited(){
alloc_visited();
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
if (maze[i][j] == '+'){
visited[i][j] = wall;
} else if (maze[i][j] == 'g'){
visited[i][j] = goal;
} else {
visited[i][j] = empty;
}
}
}
}
int dfs(int row, int col){
int* current = &visited[row][col];
if (*current == goal){
return 1;
}
if (*current == empty){
*current = crumb;
if (dfs(row, col -1)){
*current = crumb;
return 1;
}
if (dfs(row + 1,col)){
*current = crumb;
return 1;
}
if (dfs(row, col + 1)){
*current = crumb;
return 1;
}
if (dfs(row - 1, col)){
*current = crumb;
return 1;
}
}
return 0;
}
void add_crumb(){
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
if (maze[i][j] != 's'){
if (visited[i][j] ==crumb){
maze[i][j] = '.';
}
}
}
}
}
void print_visited(){
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
printf("%d", visited[i][j]);
}
printf("\n");
}
printf("\n");
}
void print_maze(){
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
printf("%c", maze[i][j]);
}
printf("\n");
}
printf("\n");
}
int main(){
get_maze("mazedata.txt");
get_visited();
print_maze();
dfs(start_row, start_col);
add_crumb();
print_maze();
return 0;
}
My data file for the maze is here Data file