2017-02-22 52 views
-2

Первое сообщение о переполнении стека должно быть приятным. Я пытаюсь написать программу для школы. Эта программа предполагает взять набор данных и превратить его в лабиринт. Ошибка, которую я получаю, - это ошибка сегментации в шпаклере, но не в среде IDE, которую я использую. Не уверен, что делать или как с этим справиться. Я пробовал делать заявления printf повсюду, но ни один из них действительно не появился, не имеет смысла. Может быть, потому, что сами функции вызывают непонимание, хотя какая часть.Связанные списки и стеки и ошибка сегментации

// КОД НАЧИНАЕТ ****************************************** **********************

#include <stdio.h> 
#include <stdlib.h> 
typedef int bool; 
#define FALSE 0 
#define TRUE 1 

typedef struct mazeStruct 
{ 
    char **arr; /* allows for a dynamic 2-D maze of any size */ 
    int xsize, ysize; 
    int xstart, ystart; 
    int xend, yend; 
    bool end; 
} maze; 

struct linkedStruct 
{ 
    int x; 
    int y; 
    bool Unvisited; 
    struct linkedStruct* next; 
}; 

typedef struct linkedStruct linked; 
typedef linked* linkedPtr; 

void push(linkedPtr* hd, int Xval, int Yval) 
{ 
    linkedPtr ptr = (linkedPtr) malloc(sizeof(linked)); 
    ptr->x = Xval; 
    ptr->y = Yval; 
    ptr->Unvisited = FALSE; 
    ptr->next = *hd; 
    *hd = ptr; 
} 

int isEmpty(linkedPtr hd) 
{ 
    if (hd == NULL) 
     return TRUE; 
    else 
     return FALSE; 
} 

int top(linkedPtr hd) 
{ 
    return (hd->x && hd->y); 
} 

void pop(linkedPtr* hd) 
{ 
    linkedPtr ptr = (linkedPtr) malloc(sizeof(linked)); 

    ptr->x = NULL; 
    ptr->y = NULL; 
    ptr->Unvisited = TRUE; 
    ptr->next = *hd; 
    *hd = ptr; 
    free(ptr); 
} 

int main(int argc, char **argv) 
{ 
    maze m1; 
    linkedPtr head = NULL; 

    int xpos, ypos; 
    int i, j; 
    m1.end = FALSE; 

    FILE *src; 
    //FILE *src = fopen ("mazeData1.txt",'r'); 

    /* verify the proper number of command line arguments were given */ 
    if (argc != 2) 
    { 
     printf("Usage: %s <input file name>\n", argv[0]); 
     exit(-1); 
    } 

    /* Try to open the input file. */ 
    if ((src = fopen(argv[1], "r")) == NULL) 
    { 
     printf("Can't open input file: %s", argv[1]); 
     printf("Standard Error.\n"); 
     exit(-1); 
    } 

    /* read in the size, starting and ending positions in the maze */ 
    fscanf(src, "%d %d", &m1.xsize, &m1.ysize); 
    if (m1.xsize < 1 || m1.ysize < 1) 
    { 
     printf("Size has to be 1 or above.\n"); 
     fscanf(src, "%d %d", &m1.xsize, &m1.ysize); 
    } 
    fscanf(src, "%d %d", &m1.xstart, &m1.ystart); 
    if (m1.xstart > m1.xsize || m1.ystart > m1.ysize || m1.xstart < 1 
      || m1.ystart < 1) 
    { 
     printf("The start has to be within the maze.\n"); 
     fscanf(src, "%d %d", &m1.xstart, &m1.ystart); 
    } 
    fscanf(src, "%d %d", &m1.xend, &m1.yend); 
    if (m1.xend > m1.xsize || m1.yend > m1.ysize || m1.xend < 1 || m1.yend < 1) 
    { 
     printf("The end has to be within the maze.\n"); 
     fscanf(src, "%d %d", &m1.xend, &m1.yend); 
    } 

    if (m1.xend == NULL || m1.yend == NULL) 
    { 
     printf("Error: Need at least three lines of input"); 
     exit(-1); 
    } 

    /* print them out to verify the input */ 
    printf("size: %d, %d\n", m1.xsize, m1.ysize); 
    printf("start: %d, %d\n", m1.xstart, m1.ystart); 
    printf("end: %d, %d\n", m1.xend, m1.yend); 

    /* allocate the maze */ 
    m1.arr = (char **) malloc(sizeof(char *) * (m1.xsize + 2)); 
    for (i = 0; i < m1.xsize + 2; i++) 
     m1.arr[i] = (char *) malloc(sizeof(char) * (m1.ysize + 2)); 

    /* initialize the maze to empty */ 
    for (i = 0; i < m1.xsize + 2; i++) 
     for (j = 0; j < m1.ysize + 2; j++) 
      m1.arr[i][j] = '.'; 

    /* mark the borders of the maze with *'s */ 
    for (i = 0; i < m1.xsize + 2; i++) 
    { 
     m1.arr[i][0] = '*'; 
     m1.arr[i][m1.ysize + 1] = '*'; 
    } 
    for (i = 0; i < m1.ysize + 2; i++) 
    { 
     m1.arr[0][i] = '*'; 
     m1.arr[m1.xsize + 1][i] = '*'; 
    } 

    /* mark the starting and ending positions in the maze */ 
    m1.arr[m1.xstart][m1.ystart] = 's'; 
    m1.arr[m1.xend][m1.yend] = 'e'; 

    /* mark the blocked positions in the maze with *'s */ 
    while (fscanf(src, "%d %d", &xpos, &ypos) != EOF) 
    { 
     if (xpos > m1.xsize || ypos > m1.ysize || xpos < 1 || ypos < 1 
       || (xpos == m1.xstart && ypos == m1.ystart) 
       || (xpos == m1.xend && ypos == m1.yend)) 
     { 
      printf(
        "Error: X or Y is: out of range or is on the end or is on the start\n"); 
      continue; 
     } 
     m1.arr[xpos][ypos] = '*'; 
    } 

    /* print out the initial maze */ 
    for (i = 0; i < m1.xsize + 2; i++) 
    { 
     for (j = 0; j < m1.ysize + 2; j++) 
      printf("%c", m1.arr[i][j]); 
     printf("\n"); 
    } 

    // THE START OF THE DEPTH FIRST SEARCH METHOD 
    for (i = 0; i < m1.xsize + 2; i++) 
    { 
     for (j = 0; j < m1.ysize + 2; j++) 
     { 
      if (m1.arr[i][j] != '*') 
      { 
       head->Unvisited = FALSE; 
       head->next = head->next + 1; //MAYBE 
      } 
     } 
    } 

    head->x = m1.xstart; 
    head->y = m1.ystart; 
    head->Unvisited = FALSE; 

    while ((isEmpty(head) == FALSE) && (m1.end == FALSE)) 
    { 
     if ((m1.xend == head->x) && (m1.yend == head->y)) 
     { 
      printf("The END has be found!\n"); 
      m1.end = TRUE; 
     } 
     if ((head->x + 1 && head->y) == TRUE) 
     { 
      push(&head, head->x + 1, head->y); 
     } 
     else if ((head->x - 1 && head->y) == TRUE) 
     { 
      push(&head, head->x - 1, head->y); 
     } 
     else if ((head->x && head->y + 1) == TRUE) 
     { 
      push(&head, head->x, head->y + 1); 
     } 
     else if ((head->x && head->y) == TRUE) 
     { 
      push(&head, head->x, head->y - 1); 
     } 
     else 
     { 
      pop(head); 
     } 
    } 

    if (isEmpty(head) == TRUE) 
    { 
     printf("Maze has no solution"); 
     exit(0); 
    } 
    else 
    { 
     printf("%d %d", &head); 
    } 

    printf("%d", top(head)); 

    free(m1.arr); 
    m1.arr = NULL; 

    return 1; 
} 
+0

Ты знаешь что-нибудь 'stdbool.h'? – Stargateur

+2

использовать отладчик (GDB) для отладки проблемы, это хороший способ узнать. –

+2

Связанные списки и стеки и ошибка сегментации, oh my – StoryTeller

ответ

2

Основная проблема здесь состоит в том, что вы скрываете указатель с ЬурейиМ:

typedef linked* linkedPtr; 

В основной вы объявляете

linkedPtr head = NULL; 

, но вы никогда не выделяют/malloc поел пространство для этого Varia BLE и первый кусок кода, который разыменовать он вызывает Undefined Behavior, потому что вы разыменования указателя нулевой

// THE START OF THE DEPTH FIRST SEARCH METHOD 
for (i = 0; i < m1.xsize + 2; i++) 
{ 
    for (j = 0; j < m1.ysize + 2; j++) 
    { 
     if (m1.arr[i][j] != '*') 
     { 
      head->Unvisited = FALSE; <----------BOOOOOOOOOOOOOOM------- 
      head->next = head->next + 1; 
     } 
    } 
} 

Кроме того у вас есть несоответствие типов призывающую pop функции, изменить

pop(head); 

в

pop(&head);