|
herionn
|
|
|
|
Ошибка неизвестного характера
17.03.2013, 15:59. Показов 1213. Ответов 1
Добрый день. Говорю сразу, программу писал не я. Задали сделать программу-сортировщик для чисел с приоритетами с возможностью загрузки из файла и сохранения в файл. Вроде бы, все работает, но при выходе через меню выдает вот такую ошибку.
Отладка:
| C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| "laba_1 (sda).exe": Загружено: "C:\Users\Дмитрий\Desktop\laba_1 (sda)\Debug\laba_1 (sda).exe", Символы загружены.
"laba_1 (sda).exe": Загружено: "C:\Windows\SysWOW64\ntdll.dll", Невозможно найти или открыть файл PDB
"laba_1 (sda).exe": Загружено: "C:\Windows\SysWOW64\kernel32.dll", Невозможно найти или открыть файл PDB
"laba_1 (sda).exe": Загружено: "C:\Windows\SysWOW64\KernelBase.dll", Невозможно найти или открыть файл PDB
"laba_1 (sda).exe": Загружено: "C:\Windows\SysWOW64\msvcp100d.dll", Символы загружены.
"laba_1 (sda).exe": Загружено: "C:\Windows\SysWOW64\msvcr100d.dll", Символы загружены.
"laba_1 (sda).exe": Загружено: "C:\Windows\SysWOW64\apphelp.dll", Невозможно найти или открыть файл PDB
"laba_1 (sda).exe": Выгружено: "C:\Windows\SysWOW64\apphelp.dll"
"laba_1 (sda).exe": Загружено: "C:\Windows\SysWOW64\apphelp.dll", Невозможно найти или открыть файл PDB
"laba_1 (sda).exe": Загружено: "ImageAtBase0x4a550000", Загрузка отключена параметром включения/исключения.
"laba_1 (sda).exe": Выгружено: "ImageAtBase0x4a550000"
HEAP[laba_1 (sda).exe]: Invalid address specified to RtlValidateHeap( 002C0000, 002C7BA8 )
ОС Windows инициировала точку останова в laba_1 (sda).exe.
Это может быть вызвано повреждением кучи и указывает на ошибку в laba_1 (sda).exe или в одной из загруженных им DLL.
Возможной причиной так же может быть нажатие пользователем клавиши F12, когда фокус принадлежит laba_1 (sda).exe
Выведенное на экран окно содержит дополнительные данные для диагностики ошибки |
|
И еще:
| 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
| /***
*free.c - free an entry in the heap
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* Defines the following functions:
* free() - free a memory block in the heap
*
*******************************************************************************/
#include <cruntime.h>
#include <malloc.h>
#include <winheap.h>
#include <windows.h>
#include <internal.h>
#include <mtdll.h>
#include <dbgint.h>
#include <rtcsup.h>
/***
*void free(pblock) - free a block in the heap
*
*Purpose:
* Free a memory block in the heap.
*
* Special ANSI Requirements:
*
* (1) free(NULL) is benign.
*
*Entry:
* void *pblock - pointer to a memory block in the heap
*
*Return:
* <void>
*
*******************************************************************************/
void __cdecl _free_base (void * pBlock)
{
int retval = 0;
if (pBlock == NULL)
return;
RTCCALLBACK(_RTC_Free_hook, (pBlock, 0));
retval = HeapFree(_crtheap, 0, pBlock);
if (retval == 0)
{
errno = _get_errno_from_oserr(GetLastError());
}
} |
|
Сам код:
| 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
| #include "stdafx.h"
#include <windows.h>
#include <iostream> //библиотека ввода
#include <fstream> //библиотека работы с файлами (оператор << и >>)
#include <conio.h> //распознавание функции getch(); - аналог system("pause");
#pragma hdrstop //конец заголовочных файлов
#pragma argsused //функция маин использует аргументы
#include <tchar.h> //использование символов юникод, занимающих два байта в оличии от анси, занимающих один
using namespace std;
struct Element //собсно структура Элемент очереди
{
int el; //елемент очереди
int pr; //приоритет
};
struct Cherga //собсно сама очередь)
{
Element *ElemChergy; //ее элементы. там много элементов
int LengthOfCherga; //длина очереди, кол-во этих элементов
void Create() //функция обьявления очереди
{
ElemChergy=new Element(); //выделение памяти для элементов очереди (иначе не работает=) )
LengthOfCherga=0; //стартовый размер = 0
};
void InsertWithPriority(int e, int p) // функция добавления в массив всех элементов очереди еще одного,
{
ElemChergy[LengthOfCherga].el=e; //объявление числа элемента
ElemChergy[LengthOfCherga++].pr=p; //его приоритета
Sort(); //сортировка массива по приоритету
};
void GetNext() //выдергивание из массива первого элемента
{
system("cls");
if (LengthOfCherga)
{
cout<<"\nelement=" <<ElemChergy[0].el<<"; " //вывод числа элемента очереди
<<"priority="<<ElemChergy[0].pr<<".\n"; //вывод приоритета элемента очереди
LengthOfCherga--; //уменьшение размера массива на этот выдернутый элемент
for (int i = 0; i < LengthOfCherga; i++) {
ElemChergy[i]=ElemChergy[i+1]; //сдвиг массива на 1 (выдернутый) элемент назад
}
} else
cout<<"UNDEF";
cout<<endl<<"Press any key to return to main menu...";
getch();
system("cls");
//если вдруг в очереди нет элементов - сообщить юзверю, что он не прав
};
void Sort() //сортировка массива
{
Element tmp;
int max[2];
for (int j = 0; j < LengthOfCherga; j++) {
max[0]=ElemChergy[j].el;
max[1]=j;
for (int i = j+1; i < LengthOfCherga; i++) {
if (ElemChergy[i].el>max[0]) {max[0]=ElemChergy[i].el;max[1]=i;}
}
tmp=ElemChergy[j];
ElemChergy[j]=ElemChergy[max[1]];
ElemChergy[max[1]]=tmp;
}
for (int j = 0; j < LengthOfCherga; j++) {
max[0]=ElemChergy[j].pr;
max[1]=j;
for (int i = j+1; i < LengthOfCherga; i++) {
if (ElemChergy[i].pr>max[0]) {max[0]=ElemChergy[i].pr;max[1]=i;}
}
tmp=ElemChergy[j];
ElemChergy[j]=ElemChergy[max[1]];
ElemChergy[max[1]]=tmp;
}
};
void ShowCherga() //вывод очереди
{
int i = 0, j = 0, Height = 0;
CONSOLE_SCREEN_BUFFER_INFO q;
HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE );
GetConsoleScreenBufferInfo( h , &q );
Height = q.srWindow.Bottom - q.srWindow.Top;
cout<<endl<<endl;
while (1) {
for (; i < Height && i+j*Height < LengthOfCherga; i++) {
cout<<"Element=" <<ElemChergy[i+j*Height].el<<";\t"
<<"Priority="<<ElemChergy[i+j*Height].pr<<".\n";
}
for (; i < Height; i++) {
cout<<endl;
}
if (i+j*Height>=LengthOfCherga-1) break;
else {j++;i=0;}
cout<<"Press any key to show the next page or press ctrl+c to stop";
if (getch()==3) {
cout<<endl; break;
} else
cout<<endl;
}
cout<<"Press any key to return to main menu...";
getch();
system("cls");
};
void PeekAtNext() //вывод последнего элемента очереди без выдергивания
{
system("cls");
if (LengthOfCherga)
cout<<"\nElement="<<ElemChergy[0].el<<"; "
<<"Priority=" <<ElemChergy[0].pr<<".\n";
else
cout<<"UNDEF"<<endl;
cout<<endl<<"Press any key to return to main menu...";
getch();
system("cls");
};
void Save(char *FileName)
{
ofstream fil(FileName);
if (fil==0) {throw "Error file not found!";}
for (int i = 0; i < LengthOfCherga; i++) {
fil<<"queue "<<ElemChergy[i].pr<<" "<<ElemChergy[i].el<<endl;
}
fil.close();
};
void Load(char *FileName)
{
ifstream fil(FileName,ios::in);
if (fil==0) {throw "Error file not found!";}
else cout<<"File opened.\n";
int q;
char *buf=new char();
for (;;) {
fil>>buf;
if ((char)buf[0]==113&&(char)buf[1]==117&&(char)buf[2]==101&&(char)buf[3]==117&&(char)buf[4]==101) { //todo: сравнить правильно :
fil>>q;
ElemChergy[LengthOfCherga].pr=q;
fil>>q;
ElemChergy[LengthOfCherga++].el=q;
cout<<"Element load ("<<ElemChergy[LengthOfCherga-1].pr<<","<<ElemChergy[LengthOfCherga-1].el<<")\n";
} else {
break;
}
}
Sort();
cout<<"Reading complete, number of readed elements = "<<LengthOfCherga<<", press 'y' to show cherga "
<<"or 'n' if showing is not needed:";
bool w=1;
while (w)
switch (getch())
{
case 89:
case 121:w=0;ShowCherga();break;
case 78:
case 110:w=0; break;
default:
cout<<"Illegal key. repeat, please:";
break;
};
fil.close();
};
} Cherga1;
int _tmain(int argc, _TCHAR* argv[])
{
system("title Laba #1");//объявление заголовка окна
bool rathy=true;
bool menuNeeded=true; //бит необходимости меню (работает в следующих веррсиях программы)
char fileName[128]; //считываемое имя файла с базой
char *comm=new char();
Cherga1.Create(); //создание очереди
cout<<"Hello, User!"<<endl;// приветствие
try {
if (argv[1]==0) {
cout<<"Enter the name of file ('file.txt' ready-made, 'no' for skip)"<<endl;
cin >>fileName;
if (fileName[0]=='n'&&fileName[1]=='o'&&fileName[2]==(char)0) throw "loading skipped!\n";
//вы можете отказаться от загрузки базы с очередью в любом случае
}
Cherga1.Load((argv[1]==0)?((char*)fileName):((char*)argv[1]));
//загрузка очереди из файла
} catch (const char *err) { // ловля
cout<<endl<<err<<endl; // всевозможных
} catch(...) { // ошибок
cout<<endl<<"Some error have been catched..."<<endl;
}
while (rathy)
{
if (menuNeeded)
cout<<"\nHere is a list if available commands:"<<endl
<<"1. (Showcherga);"<<endl
<<"2. (Queue) - you will need to define [priority] [element]);"<<endl
<<"3. (Min) - show the first element of cherga;"<<endl
<<"4. (Dequeue) - show & delete from cherga the first element of cherga;"<<endl
<<"5. (Dump) - save it to file. you will need to set filename"<<endl
<<"6. (Exit) - exit app"<<endl<<endl<<">";
//вывод меню
cin >>comm; //ввод номера комманды
if (comm[0]=='1') {
Cherga1.ShowCherga();
} else
if (comm[0]=='2') {
system("cls");
int q[2]={-1,-1};
cout<<"Insert priority:";
cin >>q[0];
cout<<"Insert element:";
cin >>q[1];
if (q[0]>=0&&q[1]>=0) {
Cherga1.InsertWithPriority(q[1],q[0]);
cout<<"Done!\n";
} else
cout<<"Error!\n";
getch();
system("cls");
} else
if (comm[0]=='3') {
Cherga1.PeekAtNext();
} else
if (comm[0]=='4') {
Cherga1.GetNext();
} else
if (comm[0]=='5') {
system("cls");
char *filename;
cout<<"Insert filename:";
cin>>fileName;
Cherga1.Save(fileName);
system("cls");
} else
if (comm[0]=='6') {
rathy=false;
}
}
return 0;
} |
|
Подскажите пожалуйста, в чем ошибка?
|