0 / 0 / 0
Регистрация: 20.10.2017
Сообщений: 18
1

Ошибка SIGSEGV(Segmentation fault)

26.10.2017, 21:02. Показов 3923. Ответов 3
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Задание такое:
Реализовать вычисления условных арифметических выражений c одномерными динамическими векторами, которые
содержат целочисленные элементы, длиной от 1 до 1000. Эти векторы - объекты своего класса.

Vector.h
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#ifndef OOP_CLION_VECTOR_H
#define OOP_CLION_VECTOR_H
 
#endif //OOP_CLION_VECTOR_H
 
#include <math.h>
#include <float.h>
#include <conio.h>
#include <iostream>
#include <Windows.h>
#include <string>
#include <iostream>
#include <sstream>
#include <string>
 
using namespace std;
static char *ValueOverflow = "Value overflow exception!\n";
static char *IncorrectSize = "Size of the vector is incorrect!\n";
static char *DivisionByZero = "Division by zero!\n";
 
class Vector {
    friend Vector &operator-(const int a, const Vector &b);
 
private:
    int size;
    int *num;
    char name;
 
public:
    Vector(int size);
 
    Vector(char name);
 
    Vector(int size, char name);
 
    Vector();
 
    Vector (const Vector &initial);
 
    ~Vector();
 
    void showVector();
 
    void inputVector();
 
    char getName() const;
 
    int  getSize() const;
 
    void setSize(int s);
 
    Vector operator-(const int &n);
 
    Vector operator/(const Vector &v1);
 
    const Vector& operator=(const Vector &right);
 
    const Vector& operator=(const int &n);
 
    bool operator==(const Vector &arrInt);
 
    bool operator>(const Vector &arrInt);
 
    bool operator<(const Vector &arrInt);
};


Vector.cpp
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#include "Vector.h"
#include "climits"
#include <assert.h>
 
Vector::Vector(int parSize) {
    size = parSize;
    num = new int[size];
    assert(num!=0);
    for (int i = 0; i < size; i++) {
        num[i] = 0;
    }
}
 
Vector::Vector() {
    size = 0;
    num = 0;
}
 
Vector::~Vector() {
    delete[] num;
 
}
 
void Vector::showVector() {
    for (int i = 0; i < size; i++) {
        cout << "[" << num[i] << "]";
    }
    cout << "\n";
}
 
void Vector::inputVector() {
    if (size < 1 || size > 1000) throw IncorrectSize;
 
    num = new int[size];
    for (int i = 0; i < size; i++) {
        num[i] = 0;
    }
    if (size <= 10) {
        for (int i = 0; i < this->size; i++) {
            cout << "Enter Vector " << name << "[" << i << "]: ";
            while (!(cin >> num[i])) {
                cout << "Incorrect input! Please try again." << endl;
                cout << "Enter Vector " << name << "[" << i << "]: ";
                cin.clear();
                while (cin.get() != '\n') { continue; }
            }
            while (cin.get() != '\n') { continue; }
        }
    } else {
        cout << "Vector " << name << " filled randomly!\n";
        for (int i = 0; i < size; i++) {
            num[i] = rand() % size;
        }
    }
}
 
char Vector::getName() const {
    return name;
}
 
bool Vector::operator==(const Vector &arrInt) {
    int sumArrInt = 0;
    int sumThis = 0;
    for (int i = 0; i < this->size; i++) {
        sumThis += this->num[i];
    }
    for (int i = 0; i < arrInt.size; i++) {
        sumArrInt += arrInt.num[i];
    }
    if (sumThis == sumArrInt) {
        return true;
    } else return false;
}
 
bool Vector::operator>(const Vector &arrInt) {
    int sumArrInt = 0;
    int sumThis = 0;
    for (int i = 0; i < this->size; i++) {
        sumThis += this->num[i];
    }
    for (int i = 0; i < arrInt.size; i++) {
        sumArrInt += arrInt.num[i];
    }
    if (sumThis > sumArrInt) {
        return true;
    } else return false;
}
 
bool Vector::operator<(const Vector &arrInt) {
    int sumArrInt = 0;
    int sumThis = 0;
    for (int i = 0; i < this->size; i++) {
        sumThis += this->num[i];
    }
    for (int i = 0; i < arrInt.size; i++) {
        sumArrInt += arrInt.num[i];
    }
    if (sumThis < sumArrInt) {
        return true;
    } else return false;
}
 
Vector Vector::operator-(const int &n) {
    Vector tmp(*this);
    for (int i = 0; i < size; i++) {
        long double t = 0;
        t = this->num[i] - n;
        if ((t > INT_MAX || t < INT_MIN) || t != (int) t) throw ValueOverflow;
        tmp.num[i] = (int) t;
    }
    return tmp;
}
 
Vector Vector::operator/(const Vector &v1) {
    int s = 0;
    Vector tmp;
    if (this->size > v1.size) {
        tmp = Vector(*this);
        s = this->size;
    } else {
        tmp = Vector(v1);
        s = v1.size;
    }
 
    for (int i = 0; i < s; i++) {
        if (v1.num[i] == 0) throw DivisionByZero;
        long double t = this->num[i] / v1.num[i];
        if ((t > INT_MAX || t < INT_MIN) || t != (int) t) throw ValueOverflow;
        tmp.num[i] = (int) t;
    }
    return tmp;
}
 
Vector &operator-(int a, const Vector &b) {
    Vector tmp(b.size);
    for (int i = 0; i < b.size; i++) {
        tmp.num[i] = a - b.num[i];
    }
    return tmp;
}
 
const Vector &Vector::operator=(const Vector &right) {
    if (this != &right){
    delete[] num;
    size = right.size;
    num = new int[size];
    assert(num != 0);
    for (int i = 0; i < size; i++) {
        num[i] = right.num[i];
    }
    }
    return *this;
}
 
Vector::Vector(int parSize, char parName) {
    size = parSize;
    num = new int[size];
    assert(num!=0);
    name = parName;
    for (int i = 0; i < size; i++) {
        num[i] = 0;
    }
}
 
void Vector::setSize(int parSize) {
    size = parSize;
}
 
Vector::Vector(char parName) {
    name = parName;
}
 
int Vector::getSize() const {
    return size;
}
 
const Vector& Vector::operator=(const int &n) {
    //if (v != this){
    delete[] num;
    size = 1;
    num = new int[size];
    num[0] = n;
    return *this;
}
 
Vector::Vector(const Vector &initial) {
    size = initial.size;
    num = new int[size];
    assert(num!=0);
    for (int i = 0; i < size; i++)
        num[i] = initial.num[i];
}


main.cpp
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include "Vector.h"
 
int inputSize() {
    int inpS = 0;
    while (!(cin >> inpS) || inpS < 1 || inpS > 1000) {
        cout << "Incorrect size. Try again: ";
        cin.clear();
        while (cin.get() != '\n') { continue; }
    }
    while (cin.get() != '\n') { continue; }
    return inpS;
}
 
int main() {
    int esc = 27, key = 0, t = 0, ia, ib;
    Vector *a;
    Vector *b;
    Vector *x;
    do {
        try {
            cout << "---------------------TEST#_" + to_string(++t) + "---------------------\n";
            cout << "\t 1-b/a \t\t a>b" << endl;
            cout << "\t -10 \t\t a=b" << endl;
            cout << "\t (a-52)/b \t a<b" << endl;
 
            *a = Vector('a');
            cout << "Enter size of vector " << a->getName() << " :";
            a->setSize(inputSize());
            if (a->getSize() == 1) {
                cout << "Enter element: ";
                cin >> ia;
                *a = ia;
            } else {
                a->inputVector();
            }
            a->showVector();
 
            *b = Vector('b');
            cout << "Enter size of vector " << b->getName() << " :";
            b->setSize(inputSize());
            if (b->getSize() == 1) {
                cout << "Enter element: ";
                cin >> ib;
                *b = ib;
            } else {
                b->inputVector();
            }
            b->showVector();
 
            *x = Vector('x');
 
            if (*a == *b) {
                cout << "a and b is equal!" << endl;
            } else if (*a < *b) {
                cout << "a is smaller than b!" << endl;
            } else if (*a > *b) {
                cout << "a is bigger than b!" << endl;
            }
 
            if (*a > *b) { *x = 1 - (*b / *a); }
            else if (*a == *b) { *x = -10; }
            else { *x = (*a - 52) / *b; }
            x->showVector();
 
            delete &a, &b, &x;
 
            cout << "Press Esc to exit or any other key to continue...\n";
            key = _getch();
        }
        catch (char *message) {
            cout << message << endl;
        }
        catch (...) {
            cout << "Handling unexpected exception..." << endl;
        }
    } while (key != esc);
    return 0;
}


В коде переопределения присваивания для двух векторов на строчке num[i] = right.num[i]; выдаёт ошибку SIGSEGV(Segmnetation fault), при этом программа вылетает с этой ошибко практически сразу же после запуска, т.е. сразу после того, как в консоль выведет решаемый пример. Я никак не могу понять из-за чего так происходит и почему именно здесь.
C++
1
2
3
4
5
6
7
8
9
10
11
12
const Vector &Vector::operator=(const Vector &right) { //right: const Vector &
    if (this != &right){
    delete[] num;
    size = right.size;
    num = new int[size];
    assert(num != 0);
    for (int i = 0; i < size; i++) {
        num[i] = right.num[i]; // i: 46920
    }
    }
    return *this;
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
26.10.2017, 21:02
Ответы с готовыми решениями:

SIGSEGV (Segmentation fault) в матричном калькуляторе по непонятной причине
Здравствуйте! Начал изучать Си++ на примере написания матричного калькулятора, но при запуске...

Ошибка Segmentation fault
Всем доброго дня. Люди добрые, помогите, кто чем может. При вызове метода hand.dealToPlayers(0)...

Ошибка strcat ...segmentation fault
имеется функция показывает что segmentation fault(только в режиме дебага) в красных строках...а при...

Ошибка выполнения Segmentation fault при открытии файла
Привет всем! почему не открывается файл, не понимаю что такое? ubuntu 16, qt creator 3.6.1...

3
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
26.10.2017, 22:06 2
Цитата Сообщение от st4s Посмотреть сообщение
C++
1
2
3
Vector *a;
Vector *b;
Vector *x;
Цитата Сообщение от st4s Посмотреть сообщение
C++
1
*a = Vector('a');
Память под объекты нужно выделить.
0
0 / 0 / 0
Регистрация: 20.10.2017
Сообщений: 18
26.10.2017, 22:32  [ТС] 3
Увидел через минуту как оставил пост Реишл также отказаться от имени вектора.
Но теперь почему-то у меня в случае если вектор 'a' больше, чем вектор 'b', то программа вылетает с этой же ошибкой при попытке присвоить результат в вектор 'x' (оператор присвоение вектора в вектор). Решил проверить поэтапно: деление вектора на вектор - работает как нужно, отнять от числа вектор - тоже(в целом ошибку как раз при поптыке присвоение выдаёт) В остальных случаях - всё работает как нужно.

C++
1
2
3
4
5
6
7
8
9
10
11
12
const Vector &Vector::operator=(const Vector &right) {
    if (this != &right){
    delete[] num;
    size = right.size; //ошибка возникает тут
    num = new int[size];
    assert(num != 0);
    for (int i = 0; i < size; i++) {
        num[i] = right.num[i];
    }
    }
    return *this;
}
main.cpp
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include "Vector.h"
 
int inputSize() {
    int inpS = 0;
    while (!(cin >> inpS) || inpS < 1 || inpS > 1000) {
        cout << "Incorrect size. Try again: ";
        cin.clear();
        while (cin.get() != '\n') { continue; }
    }
    while (cin.get() != '\n') { continue; }
    return inpS;
}
 
int main() {
    int esc = 27, key = 0, t = 0, ia, ib;
    Vector a;
    Vector b;
    Vector x;
    do {
        try {
            cout << "---------------------TEST#_" + to_string(++t) + "---------------------\n";
            cout << "\t 1-b/a \t\t a>b" << endl;
            cout << "\t -10 \t\t a=b" << endl;
            cout << "\t (a-52)/b \t a<b" << endl;
 
            a = Vector();
            cout << "Enter size of vector a" << " :";
            a.setSize(inputSize());
            if (a.getSize() == 1) {
                cout << "Enter element: ";
                cin >> ia;
                a = ia;
            } else {
                a.inputVector();
            }
            a.showVector();
 
            b = Vector();
            cout << "Enter size of vector b" << " :";
            b.setSize(inputSize());
            if (b.getSize() == 1) {
                cout << "Enter element: ";
                cin >> ib;
                b = ib;
            } else {
                b.inputVector();
            }
            b.showVector();
 
            x = Vector(); //against SIGSEGV error
 
            if (a == b) {
                cout << "a and b is equal!" << endl;
            } else if (a < b) {
                cout << "a is smaller than b!" << endl;
            } else if (a > b) {
                cout << "a is bigger than b!" << endl;
            }
 
            if (a > b) { x = 1 - (b / a); }
            else if (a == b) { x = -10; }
            else { x = (a - 52) / b; }
            x.showVector();
 
            delete &a, &b, &x;
 
            cout << "Press Esc to exit or any other key to continue...\n";
            key = _getch();
        }
        catch (char *message) {
            cout << message << endl;
        }
        catch (...) {
            cout << "Handling unexpected exception..." << endl;
        }
    } while (key != esc);
    return 0;
}


Vector.h
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#ifndef OOP_CLION_VECTOR_H
#define OOP_CLION_VECTOR_H
 
#endif //OOP_CLION_VECTOR_H
 
#include <math.h>
#include <float.h>
#include <conio.h>
#include <iostream>
#include <Windows.h>
#include <string>
#include <iostream>
#include <sstream>
#include <string>
 
using namespace std;
static char *ValueOverflow = "Value overflow exception!\n";
static char *IncorrectSize = "Size of the vector is incorrect!\n";
static char *DivisionByZero = "Division by zero!\n";
 
class Vector {
    friend Vector &operator-(const int a, const Vector &b);
 
private:
    int size;
    int *num;
 
public:
 
    Vector(int size);
 
    Vector();
 
    Vector (const Vector &initial);
 
    ~Vector();
 
    void showVector();
 
    void inputVector();
 
    int  getSize() const;
 
    void setSize(int s);
 
    Vector operator-(const int &n);
 
    Vector operator/(const Vector &v1);
 
    const Vector &operator=(const Vector &right);
 
    const Vector& operator=(const int &n);
 
    bool operator==(const Vector &arrInt);
 
    bool operator>(const Vector &arrInt);
 
    bool operator<(const Vector &arrInt);
};


Vector.cpp
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#include "Vector.h"
#include "climits"
#include <assert.h>
 
Vector::Vector(int parSize) {
    size = parSize;
    num = new int[size];
    assert(num!=0);
    for (int i = 0; i < size; i++) {
        num[i] = 0;
    }
}
 
Vector::Vector() {
    size = 0;
    num = 0;
}
 
Vector::~Vector() {
    delete [ ] num;
 
}
 
void Vector::showVector() {
    for (int i = 0; i < size; i++) {
        cout << "[" << num[i] << "]";
    }
    cout << "\n";
}
 
void Vector::inputVector() {
    if (size < 1 || size > 1000) throw IncorrectSize;
 
    num = new int[size];
    for (int i = 0; i < size; i++) {
        num[i] = 0;
    }
    if (size <= 10) {
        for (int i = 0; i < this->size; i++) {
            cout << "Enter Vector " << "[" << i << "]: ";
            while (!(cin >> num[i])) {
                cout << "Incorrect input! Please try again." << endl;
                cout << "Enter Vector " << "[" << i << "]: ";
                cin.clear();
                while (cin.get() != '\n') { continue; }
            }
            while (cin.get() != '\n') { continue; }
        }
    } else {
        cout << "Vector "<< " filled randomly!\n";
        for (int i = 0; i < size; i++) {
            num[i] = rand() % size;
        }
    }
}
bool Vector::operator==(const Vector &arrInt) {
    int sumArrInt = 0;
    int sumThis = 0;
    for (int i = 0; i < this->size; i++) {
        sumThis += this->num[i];
    }
    for (int i = 0; i < arrInt.size; i++) {
        sumArrInt += arrInt.num[i];
    }
    if (sumThis == sumArrInt) {
        return true;
    } else return false;
}
 
bool Vector::operator>(const Vector &arrInt) {
    int sumArrInt = 0;
    int sumThis = 0;
    for (int i = 0; i < this->size; i++) {
        sumThis += this->num[i];
    }
    for (int i = 0; i < arrInt.size; i++) {
        sumArrInt += arrInt.num[i];
    }
    if (sumThis > sumArrInt) {
        return true;
    } else return false;
}
 
bool Vector::operator<(const Vector &arrInt) {
    int sumArrInt = 0;
    int sumThis = 0;
    for (int i = 0; i < this->size; i++) {
        sumThis += this->num[i];
    }
    for (int i = 0; i < arrInt.size; i++) {
        sumArrInt += arrInt.num[i];
    }
    if (sumThis < sumArrInt) {
        return true;
    } else return false;
}
 
Vector Vector::operator-(const int &n) {
    Vector tmp(*this);
    for (int i = 0; i < size; i++) {
        long double t = 0;
        t = this->num[i] - n;
        if ((t > INT_MAX || t < INT_MIN) || t != (int) t) throw ValueOverflow;
        tmp.num[i] = (int) t;
    }
    return tmp;
}
 
Vector Vector::operator/(const Vector &v1) {
    int s = 0;
    Vector tmp;
    if (this->size > v1.size) {
        tmp = Vector(*this);
        s = v1.size;
    } else {
        tmp = Vector(v1);
        s = this->size;
    }
 
    for (int i = 0; i < s; i++) {
        if (v1.num[i] == 0) throw DivisionByZero;
        long double t = this->num[i] / v1.num[i];
        if ((t > INT_MAX || t < INT_MIN) || t != (int) t) throw ValueOverflow;
        tmp.num[i] = (int) t;
    }
    return tmp;
}
 
Vector &operator-(int a, const Vector &b) {
    Vector tmp(b.size);
    for (int i = 0; i < b.size; i++) {
        tmp.num[i] = a - b.num[i];
    }
    return tmp;
}
 
const Vector &Vector::operator=(const Vector &right) {
    if (this != &right){
    delete[] num;
    size = right.size;
    num = new int[size];
    assert(num != 0);
    for (int i = 0; i < size; i++) {
        num[i] = right.num[i];
    }
    }
    return *this;
}
 
void Vector::setSize(int parSize) {
    size = parSize;
}
 
 
int Vector::getSize() const {
    return size;
}
 
const Vector& Vector::operator=(const int &n) {
    delete[] num;
    size = 1;
    num = new int[size];
    num[0] = n;
    return *this;
}
 
Vector::Vector(const Vector &initial) {
    size = initial.size;
    num = new int[size];
    assert(num!=0);
    for (int i = 0; i < size; i++)
        num[i] = initial.num[i];
}


Добавлено через 6 минут
nonedark2008, немогу пока предположить даже почему так
0
1394 / 1023 / 325
Регистрация: 28.07.2012
Сообщений: 2,813
27.10.2017, 00:16 4
Цитата Сообщение от st4s Посмотреть сообщение
Vector &operator-(int a, const Vector &b)
Возвращается ссылка на временный объект.
0
27.10.2017, 00:16
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
27.10.2017, 00:16
Помогаю со студенческими работами здесь

Ошибка "Segmentation fault" при организации дерева
Есть следующие функции Three сreateThree(Node **q) { if((*q)-&gt;p) { Three...

Ошибка "Segmentation fault" при вызове метода erase() контейнера vector
Хочу убрать изолированные вершины в графе. На строке 75 выдает &quot;Segmentation fault&quot;. #include...

Segmentation fault :(
#include&lt;iostream&gt; #include&lt;fstream&gt; using namespace std; struct test{ int id; char name;...

Segmentation fault
Доброго времени суток. Столкнулся в программе с ошибкой Segmentation fault. Вообще, задача...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru