Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.80/5: Рейтинг темы: голосов - 5, средняя оценка - 4.80
0 / 0 / 0
Регистрация: 20.10.2017
Сообщений: 18

Почему вызываються эти исключения?

18.01.2018, 17:27. Показов 1093. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Сама по себе программа работает как нужно, но после завершения работы(по идее сразу при удалении обьектов класса Vector), триггерит брейкпоинт, который, судя по всему, связан с управлением памятью.
Вот что выводит Debug:
Кликните здесь для просмотра всего текста

'OOPPR5.exe' (Win32): Loaded 'D:\OOPPR5\OOPPR5\Debug\OOPPR5.exe'. Symbols loaded.
'OOPPR5.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Symbols loaded.
'OOPPR5.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'. Symbols loaded.
'OOPPR5.exe' (Win32): Unloaded 'C:\Windows\SysWOW64\kernel32.dll'
'OOPPR5.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'. Symbols loaded.
'OOPPR5.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'. Symbols loaded.
'OOPPR5.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp140d.dll'. Symbols loaded.
'OOPPR5.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ucrtbased.dll'. Symbols loaded.
'OOPPR5.exe' (Win32): Loaded 'C:\Windows\SysWOW64\vcruntime140d.dll'. Symbols loaded.
'OOPPR5.exe' (Win32): Loaded 'C:\Windows\SysWOW64\vcruntime140d.dll'. Symbols loaded.
'OOPPR5.exe' (Win32): Unloaded 'C:\Windows\SysWOW64\vcruntime140d.dll'
Object <Vector> has been created!
Object <Vector> has been created!
Object <Vector> has been created!
Debug started...
Object <Vector> has been created!
Object <Vector> has been destroyed!
Object <Vector> has been created!
Object <Vector> has been destroyed!
Object <Vector> has been created(Copy constructor)!
Object <Vector> has been created(Copy constructor)!
Object <Vector> has been destroyed!
Object <Vector> has been created!
Object <Vector> has been created(Copy constructor)!
Object <Vector> has been destroyed!
There is might be division by zero...
Object <Vector> has been created(Copy constructor)!
Object <Vector> has been destroyed!
Object <Vector> has been destroyed!
Object <Vector> has been destroyed!
Object <Vector> has been destroyed!
Exception thrown at 0x547A121C (ucrtbased.dll) in OOPPR5.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC.
Unhandled exception thrown: read access violation.
**it** was 0xCCCCCCCC.

Exception thrown at 0x547A121C (ucrtbased.dll) in OOPPR5.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC.
Unhandled exception thrown: read access violation.
**it** was 0xCCCCCCCC.

Exception thrown at 0x547A121C (ucrtbased.dll) in OOPPR5.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC.
Unhandled exception thrown: read access violation.
**it** was 0xCCCCCCCC.

Exception thrown at 0x547A121C (ucrtbased.dll) in OOPPR5.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC.
Unhandled exception thrown: read access violation.
**it** was 0xCCCCCCCC.

Exception thrown at 0x547A121C (ucrtbased.dll) in OOPPR5.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC.
Unhandled exception thrown: read access violation.
**it** was 0xCCCCCCCC.

Exception thrown at 0x547A121C (ucrtbased.dll) in OOPPR5.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC.
Unhandled exception thrown: read access violation.
**it** was 0xCCCCCCCC.

The program '[3348] OOPPR5.exe' has exited with code 0 (0x0).


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
#pragma once
#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);
    friend ostream &operator<<(ostream &output, const Vector &v);
    friend istream &operator>>(istream &input, Vector &v);
 
private:
    int size;
    int *num;
public:
 
    Vector(int size);
 
    Vector();
 
    Vector(const Vector &initial);
 
    ~Vector();
 
    int  getSize() const;
 
    void setSize(int s);
 
    int &operator[](int iterator);
 
    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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#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;
    }
#ifdef OutputDebugString
    OutputDebugStringA("Object <Vector> has been created!(Size parameter) \n");
#endif // DEBUG
}
 
Vector::Vector() {
    size = 0;
    num = 0;
#ifdef OutputDebugString
    OutputDebugStringA("Object <Vector> has been created! \n");
#endif // DEBUG
}
 
Vector::~Vector() {
    delete[] num;
#ifdef OutputDebugString
    OutputDebugStringA("Object <Vector> has been destroyed! \n");
#endif // DEBUG
}
 
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;
    }
#ifdef OutputDebugString
    OutputDebugStringA("There is might be division by zero... \n");
#endif // DEBUG
    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) {
    if (size == 0)
    {
        size = 1;
        num = new int[size];
        assert(num != 0);
        num[0] = n;
    }
    else
    {
        for (int i = 0; i < size; i++)
        {
            num[i] = 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];
#ifdef OutputDebugString
    OutputDebugStringA("Object <Vector> has been created(Copy constructor)! \n");
#endif // DEBUG
}
 
ostream &operator<<(ostream &output, const Vector &v) {
    int i;
    for (i = 0; i < v.size; i++)
    {
        output << '[' << v.num[i] << ']' << " ";
        if ((i + 1) % 10 == 0) output << endl;
    }
    if (i % 10 != 0) output << endl;
    return output;
}
 
istream &operator>>(istream &input, Vector &v) {
    if (v.size < 1 || v.size > 1000) throw IncorrectSize;
 
    v.num = new int[v.size];
    for (int i = 0; i < v.size; i++) {
        v.num[i] = 0;
    }
    if (v.size <= 10) {
        for (int i = 0; i < v.size; i++) {
            cout << "Enter Vector " << "[" << i << "]: ";
            while (!(input >> v.num[i])) {
                cout << "Incorrect input! Please try again." << endl;
                cout << "Enter Vector " << "[" << i << "]: ";
                cin.clear();
                while (input.get() != '\n') { continue; }
            }
            while (input.get() != '\n') { continue; }
        }
    }
    else {
        cout << "Vector " << " filled randomly!\n";
        for (int i = 0; i < v.size; i++) {
            v.num[i] = rand() % v.size;
        }
    }
    return input;
}
 
int &Vector::operator[](int iterator) {
    assert(0 <= iterator && iterator > size);
    return num[iterator];
}

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
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
#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;
 
    do {
        Vector a;
        Vector b;
        Vector x;
        try {
#ifdef OutputDebugString
            OutputDebugStringA("Debug started... \n");
#endif // DEBUG
 
            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.setSize(inputSize());
            if (a.getSize() == 1)
            {
                cout << "Enter element: ";
                cin >> ia;
                a = ia;
            }
            else
            {
                cin >> a;
            }
            cout << a;
 
            b = Vector();
            cout << "Enter size of vector" << ": ";
            b.setSize(inputSize());
            if (b.getSize() == 1) {
                cout << "Enter element: ";
                cin >> ib;
                b = ib;
            }
            else
            {
                cin >> b;
            }
            cout << b;
 
            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)
            {
                if (a.getSize() > b.getSize())
                {
                    x = Vector(a.getSize());
                }
                else if (a.getSize() < b.getSize())
                {
                    x = Vector(b.getSize());
                }
                else if (a.getSize() == b.getSize())
                {
                    x = Vector(a.getSize());
                }
                x = -10;
            }
            else {
                x = (a - 52) / b;
            }
        }
 
        catch (char *message)
        {
            cout << message << endl;
        }
        catch (...)
        {
            cout << "Handling unexpected exception..." << endl;
        }
        cout << x;
 
        cout << "Press Esc to exit or any other key to continue...\n";
        key = _getch();
 
        delete &a;
        delete &b;
        delete &x;
    } while (key != esc);
    return 0;
}

Я немогу разобраться почему эта ошибка вызываеться. И приграмма продолжит сыпать ошибками памяти, пока не я не остановлю вручную её.
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
18.01.2018, 17:27
Ответы с готовыми решениями:

Как бросать эти исключения?
throw popOnEmpty();, throw pushOnFull(Value);. Что нибудь надо выше заинкладить/написать? Что именно?

Почему не перехватываются исключения?
Есть вот такой код, делал по учебнику Бьярне Страуструпа. Но почему-то он не перехватывает исключения... Что я делаю не так? void...

Вызываются исключения, но не могу понять почему
Не могу понять почему при значениях m и n больших 20 вызываются исключения. Такого рода: Вызвано исключение по адресу 0x00041D1E в №1.exe:...

2
 Аватар для igorrr37
2893 / 2040 / 992
Регистрация: 21.12.2010
Сообщений: 3,790
Записей в блоге: 9
19.01.2018, 08:49
C++
1
2
3
delete &a;
        delete &b;
        delete &x;
1
 Аватар для Kastaneda
5232 / 3205 / 362
Регистрация: 12.12.2009
Сообщений: 8,143
Записей в блоге: 2
19.01.2018, 12:35
Цитата Сообщение от st4s Посмотреть сообщение
Почему вызываються эти исключения?
ТСЯ!!!
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
19.01.2018, 12:35
Помогаю со студенческими работами здесь

Вызываются исключения, не могу понять почему
Это в библиотеке fstream _Myt *close() { // close the C stream _Myt *_Ans = this; if (_Myfile == 0) _Ans = 0; else ...

Почему выдает эти ошибки?
error: invalid types ‘float ’ for array subscript error: size of array ‘arr’ has non-integral type ‘float’ #include &lt;iostream&gt; ...

Почему не любят кидать исключения из деструктора?
Всем привет! Есть такое широко распространенное мнение, что бросать исключения из деструкторов - плохая идея. Почему плохая? ...

Почему не выводит текст исключения?
using System; namespace Example { class Program { public static int BadFactorial(int k) { return BadFactorial(k -...

Почему нельзя обрабатывать исключения в потоках
Сижу читаю msdn: http://msdn.microsoft.com/ru-ru/library/6kac2kdh.aspx Пять раз перечитал эти предложения плюс 2 раза перечитал...


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

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
Оттенки серого
Argus19 18.03.2026
Оттенки серого Нашёл в интернете 3 прекрасных модуля: Модуль класса открытия диалога открытия/ сохранения файла на Win32 API; Модуль класса быстрого перекодирования цветного изображения в оттенки. . .
SDL3 для Desktop (MinGW): Рисуем цветные прямоугольники с помощью рисовальщика SDL3 на Си и C++
8Observer8 17.03.2026
Содержание блога Финальные проекты на Си и на C++: finish-rectangles-sdl3-c. zip finish-rectangles-sdl3-cpp. zip
Символические и жёсткие ссылки в Linux.
algri14 15.03.2026
Существует два типа ссылок — символические и жёсткие. Ссылка в Linux — это запись в каталоге, которая может указывать либо на inode «файла-ИСТОЧНИКА», тогда это будет «жёсткая ссылка» (hard link),. . .
[Owen Logic] Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора
ФедосеевПавел 14.03.2026
Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора ВВЕДЕНИЕ Выполняя задание на управление насосной группой заполнения резервуара,. . .
делаю науч статью по влиянию грибов на сукцессию
anaschu 13.03.2026
прикрепляю статью
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru