2015-06-25 5 views
-3

У меня есть ноутбук, на котором я установил openSUSE 13.2 месяц назад. Когда я пытаюсь запустить эту программу на C++ для печати кратчайшего пути, я получаю ошибку сегментации. С другой стороны, мой код отлично работает на моем компьютере, на котором установлен Ubuntu.Моя программа дает ошибку сегментации в openSUSE

Вот результат я получаю в Ubuntu ...

[email protected]:~/Dropbox/cprog/Arrayss/2D$ uname -a 
Linux Symantha 3.13.0-53-generiC#89-Ubuntu SMP Wed May 20 10:34:28 UTC 2015 i686 i686 i686 GNU/Linux 
[email protected]:~/Dropbox/cprog/Arrayss/2D$ g++ 16.cpp 
[email protected]:~/Dropbox/cprog/Arrayss/2D$ ./a.out 
Enter total rows : 4 
Enter total cols : 4 
Enter array -> 
1 0 0 0 
1 1 1 0 
0 1 1 0 
1 1 1 1 
Input Ok .. 
Enter source row: 0 
Enter source col: 0 
Enter destination row: 3 
Enter destination col: 3 
Shortest Path -->> 
path : (0, 0) -> (1, 0) -> (1, 1) -> (1, 2) -> (2, 2) -> (3, 2) -> (3, 3) 

Но в OpenSUSE, я получаю это ...

[email protected]:~/Dropbox/cprog/Arrayss/2D> uname -a 
Linux linux-zdor.site 3.16.7-21-desktop #1 SMP PREEMPT Tue Apr 14 07:11:37 UTC 2015 (93c1539) x86_64 x86_64 x86_64 GNU/Linux 
[email protected]:~/Dropbox/cprog/Arrayss/2D> g++ 16.cpp 
[email protected]:~/Dropbox/cprog/Arrayss/2D> ./a.out 
Enter total rows : 4 
Enter total cols : 4 
Enter array -> 
1 0 0 0 
1 1 1 0 
0 1 1 0 
1 1 1 1 
Input Ok .. 
Enter source row: 0 
Enter source col: 0 
Enter destination row: 3 
Enter destination col: 3 
Shortest Path -->> 
Segmentation fault 

Может кто-нибудь сказать мне, что случилось с моим кодом? Вот мой код:

https://drive.google.com/file/d/0BzLbrlYg9GyXd3E4WnFWc3lGVUk/view?usp=sharing

#include <iostream> 
#include <unistd.h> 
using namespace std; 

#define MAXROW 10 
#define MAXCOL 10 

class Cell { 
public: 
    int row; 
    int col; 
    Cell() { } 
    Cell(int rr, int cc) : row(rr), col(cc) { } 
    bool operator==(const Cell& cc) { 
    if(row == cc.row && col == cc.col) 
     return true; 
    else 
     return false; 
    } 
}; 

class Path { 
    int row[MAXROW*MAXROW]; 
    int col[MAXCOL*MAXCOL]; 
    int size; 
public: 
    Path() : size(0) { } 
    Path(Path& pp) { 
    size = pp.size; 
    for(int i = 0; i < size; i++) { 
     row[i] = pp.row[i]; 
     col[i] = pp.col[i]; 
    } 
    } 
    Path& operator=(const Path& pp) { 
    size = pp.size; 
    for(int i = 0; i < size; i++) { 
     row[i] = pp.row[i]; 
     col[i] = pp.col[i]; 
    } 
    } 
    int length() { 
    return size; 
    } 
    void setSize(int ss) { 
    size = ss; 
    } 
    void insert(int rr, int cc) { 
    row[size] = rr; 
    col[size] = cc; 
    size++; 
    } 
    void print() { 
    int i = 0; 
    cout << "path : "; 
    while(i < size) { 
     cout << " (" << row[i] << ", " 
      << col[i] << ") "; 
     if(i < size-1) 
     cout << "-> "; 
     i++; 
    } 
    cout << endl; 
    } 
    bool searchCell(Cell c) { 
    int i = 0; 
    while(i < size) { 
     if(row[i] == c.row && col[i] == c.col) 
     return true; 
     i++; 
    } 
    return false; 
    } 
    Cell start() { 
    return Cell(row[0], col[0]); 
    } 
    Cell end() { 
    if(size > 0) 
     return Cell(row[size-1], col[size-1]); 
    else 
     return Cell(-1, -1); 
    } 
}; 


Path shortestPath(int arr[][MAXCOL], int, int, Cell, Cell, Path); 
void inputArr(int arr[][MAXCOL], int mR, int mC); 


int main() { 
    int arr[10][10], mR, mC, r, c; 
    Path p; 
    cout << "Enter total rows : "; 
    cin >> mR; 
    cout << "Enter total cols : "; 
    cin >> mC; 
    cout << "Enter array ->\n"; 
    inputArr(arr, mR, mC); 
    cout << "Input Ok ..\n"; 
    cout << "Enter source row: "; 
    cin >> r; 
    cout << "Enter source col: "; 
    cin >> c; 
    Cell source(r, c); 
    cout << "Enter destination row: "; 
    cin >> r; 
    cout << "Enter destination col: "; 
    cin >> c; 
    Cell destination(r, c); 
    cout << "Shortest Path -->>\n"; 
    p = shortestPath(arr, mR, mC, source, destination, p); 
    p.print(); 
    return 0; 
} 

Path shortestPath(int arr[][MAXCOL], int mR, int mC, Cell current, Cell target, Path p) { 
    int i = current.row; 
    int j = current.col; 
    Path p_array[4]; 
    if(arr[i][j] == 0 || i == mR || j == mC || i < 0 || j < 0 
    || p.searchCell(current)) { 
    p.setSize(0); 
    return p; 
    } 
    p.insert(i, j); 
    if(i == target.row && j == target.col) 
    return p; 
    else { 
    // Since there are four possible directions 
    p_array[0] = shortestPath(arr, mR, mC, Cell(i, j+1), target, p); 
    p_array[1] = shortestPath(arr, mR, mC, Cell(i+1, j), target, p); 
    p_array[2] = shortestPath(arr, mR, mC, Cell(i, j-1), target, p); 
    p_array[3] = shortestPath(arr, mR, mC, Cell(i-1, j), target, p); 
    int minIndex, minSize, i; 
    for(i = 0; i < 4; i++) { 
     if(p_array[i].length() != 0 && p_array[i].end() == target) { 
     minIndex = i; 
     minSize = p_array[i].length(); 
     break; 
     } 
    }  
    for(i = 0; i < 4; i++) { 
     if(p_array[i].length() < minSize && p_array[i].end() == target) { 
     minIndex = i; 
     minSize = p_array[i].length(); 
     } 
    } 
    return p_array[minIndex]; 
    } 
} 

void inputArr(int arr[][MAXCOL], int mR, int mC) { 
    int i, j; 
    for(i = 0; i < mR; i++) 
    for(j = 0; j < mC; j++) 
     cin >> arr[i][j]; 
} 
+4

запустить отладчик, проверить, где он выбрасывает – Hcorg

+1

Это не так, как работает Stackoverflow. Прочтите [ask] информацию о том, как задать хороший вопрос. – dandan78

+0

Прошу прощения, это мой первый раз. –

ответ

0

У вас есть проверки СУИ упорядоченная в вашей shortestPath функции:

if (arr[i][j] == 0 || i == mR || j == mC || i < 0 || j < 0 
    || p.searchCell(current)) { 

Вы получаете доступ массив из границ перед проверкой ли оценки являются действительный. Это неопределенное поведение, и разные системы могут вести себя по-разному при наличии неопределенного поведения (так что сбои и появление на работе являются действительными ответами на вызов неопределенного поведения).

Перепишите условие, чтобы проверить, что индексы в порядке до доступа к массиву.

if (i == mR || j == mC || i < 0 || j < 0 || arr[i][j] == 0 
    || p.searchCell(current)) { 

Это может быть не единственная проблема; это одна проблема.


Когда я беру свой код дословно вопрос и собрать его, я получаю предупреждение компиляции (ошибки, так как я использую -Werror преобразовать предупреждения в ошибки).

$ g++ -O3 -g -std=c++11 -Wall -Wextra -Werror 16.cpp -o 16 
16.cpp: In member function ‘Path& Path::operator=(const Path&)’: 
16.cpp:41:3: error: no return statement in function returning non-void [-Werror=return-type] 
    } 
^
16.cpp: In function ‘Path shortestPath(int (*)[10], int, int, Cell, Cell, Path)’: 
16.cpp:143:40: error: ‘minSize’ may be used uninitialized in this function [-Werror=maybe-uninitialized] 
     if(p_array[i].length() < minSize && p_array[i].end() == target) { 
             ^
16.cpp:29:15: error: ‘minIndex’ may be used uninitialized in this function [-Werror=maybe-uninitialized] 
    size = pp.size; 
      ^
16.cpp:134:9: note: ‘minIndex’ was declared here 
    int minIndex, minSize, i; 
     ^
cc1plus: all warnings being treated as errors 
$ 

Это серьезные проблемы и может послужить причиной того, что ваш код будет сгинуть. Конечно, вам нужно исправить это, прежде чем делать что-то еще.

Хочу отметить, что у вас есть:

class Path { 
    int row[MAXROW*MAXROW]; 
    int col[MAXCOL*MAXCOL]; 

На данный момент MAXROW == MAXCOL так есть такое же количество элементов в row и col, но если цифры были разными, вы не могли бы быть в состоянии хранить все члены пути в одном или другом из двух массивов. Не так хорошо, как хотелось бы. Массивы должны быть одинакового размера безоговорочно.Кроме того, в main(), вы определяете:

int arr[10][10], … 

, который должен, конечно, быть:

int arr[MAXROW][MAXCOL], … 

С минимальным fixups, установка minIndex = -1 и minSize = -1 в shortestPath() и добавлении return *this; к оператору присваивания, и затем добавить диагностики печати в конце shortestPath():

Path shortestPath(int arr[][MAXCOL], int mR, int mC, Cell current, Cell target, Path p) { 
    int i = current.row; 
    int j = current.col; 
    Path p_array[4]; 
    cerr << "-->> shortestPath(" << i << "," << j << ")\n"; 
    //if(arr[i][j] == 0 || i == mR || j == mC || i < 0 || j < 0 
    if (i == mR || j == mC || i < 0 || j < 0 || arr[i][j] == 0 || p.searchCell(current)) { 
    p.setSize(0); 
    cerr << "<<-- shortestPath() - 1\n"; 
    return p; 
    } 
    p.insert(i, j); 
    if (i == target.row && j == target.col) 
    { 
    cerr << "<<-- shortestPath() - 2\n"; 
    return p; 
    } 
    else { 
    // Since there are four possible directions 
    p_array[0] = shortestPath(arr, mR, mC, Cell(i, j+1), target, p); 
    p_array[1] = shortestPath(arr, mR, mC, Cell(i+1, j), target, p); 
    p_array[2] = shortestPath(arr, mR, mC, Cell(i, j-1), target, p); 
    p_array[3] = shortestPath(arr, mR, mC, Cell(i-1, j), target, p); 
    int minIndex = -1, minSize = -1, i; 
    for(i = 0; i < 4; i++) { 
     if(p_array[i].length() != 0 && p_array[i].end() == target) { 
     minIndex = i; 
     minSize = p_array[i].length(); 
     cerr << "1: minIndex: " << minIndex << ", minSize: " << minSize << "\n"; 
     break; 
     } 
    } 
    for(i = 0; i < 4; i++) { 
     if(p_array[i].length() < minSize && p_array[i].end() == target) { 
     minIndex = i; 
     minSize = p_array[i].length(); 
     cerr << "2: minIndex: " << minIndex << ", minSize: " << minSize << "\n"; 
     } 
    } 
    cerr << "3: minIndex: " << minIndex << "\n"; 
    cerr << "<<-- shortestPath() - 3\n"; 
    return p_array[minIndex]; 
    } 
} 

и запустить его, часть продукции является:

-->> shortestPath(2,0) 
<<-- shortestPath() - 1 
3: minIndex: -1 
<<-- shortestPath() - 3 

Oops: доступ и возвращение p_array[-1] не является хорошей идеей. У вас есть индексы из-под контроля - мало что удивительно. Вам нужно медитировать на код, не устанавливая minIndex на значение, отличное от -1 и что с этим делать.

+0

Нет, он все еще не работает. Но спасибо, что указали на эту проблему. –

+0

Когда я запускаю gdb, я получаю следующее: -> Программный сигнал SIGSEGV, ошибка сегментации. 0x00000000004011f4 в пути :: Путь (this = 0x7ffffffffe0, pp = ...) на 16.cpp: 29 29 size = pp.size; –

+0

Да! Наконец ... Это сработало. Большое спасибо Джонатан –

Смежные вопросы