1 / 1 / 2
Регистрация: 06.11.2011
Сообщений: 68
1

Утечка памяти (Expression: _CrtIsValidHeapPointer(pUserData))

03.05.2012, 23:52. Показов 14963. Ответов 27
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Добрый вечер всем. Столкнулся с такой проблемой. Запускаю программу, открываеться пустая консоль, увеличиваеться употребление оперативной памяти для программы и викидает такую ошибку:
Утечка памяти (Expression: _CrtIsValidHeapPointer(pUserData))

Вот код проекта:
.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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#pragma once
 
class HeatingSystem
{
public:
    virtual void ShowInformation() = 0;
    virtual void SetInformation() = 0;
};
 
class Kotel: public HeatingSystem
{
public:
    char* NameOfKotel;
    char* TypeOfKotel;
    char* MadeIn;
    int AreaOfHeating;
    int PowerOfKotelInKwat;
    int PerformanceOfHotWater;
    int PowerOfElecticity;
 
    void ShowInformation();
    void SetInformation();
    static vector<Kotel> GetVehiclesFromFile(char* fileName);
    static void SaveVehiclesToFile();
 
};
 
class Route: public HeatingSystem
{
public:
    char* NameOfKotelRoute;
    int LevelOfTempWater;
    int LevelOfTempRoom;
    int LevelOfPressure;
    vector<Kotel> Kotels;
 
    void ShowInformation();
    void SetInformation();
    static vector <Route> GetDataFromFile();
    static void SaveRoutesToFile();
};
 
vector<Route> Routes;
 
 
//vector <Route> Routes;
//
//vector<Kotel> FreeKotels;
 
void Kotel::SetInformation()
{
    Kotel kotel;
    cout<<"Enter the name: ";
    kotel.NameOfKotel = "";
    cin>>kotel.NameOfKotel;
 
    cout<<"Enter the type: ";
    cin>>kotel.TypeOfKotel;
 
    cout<<"Enter the area of heating: ";
    cin>>kotel.AreaOfHeating;
 
    cout<<"Enter the power of kotel in kWat: ";
    cin>>kotel.PowerOfKotelInKwat;
 
    cout<<"Enter the performance of hot water: ";
    cin>>kotel.PerformanceOfHotWater;
 
    cout<<"Enter the power of electricity: ";
    cin>>kotel.PowerOfElecticity;
 
    cout<<"Enter the country where kotel was made: ";
    cin>>kotel.MadeIn;
 
    Kotel::SaveVehiclesToFile();
}
 
void Route::SetInformation()
{
    Route route;
 
    cout<<"Enter the name: ";
    route.NameOfKotelRoute = new char;
    cin>>route.NameOfKotelRoute;
 
    cout<<"Enter the level of temperature of water: ";
    cin>>route.LevelOfTempWater;
 
    cout<<"Enter the level of temperature of room: ";
    cin>>route.LevelOfTempRoom;
 
    cout<<"Enter the pressure: ";
    cin>>route.LevelOfPressure;
 
    Routes.push_back(route);
 
    SaveRoutesToFile();
    delete [] route.NameOfKotelRoute;
}
 
#pragma region Kotel Methods
 
vector<Route> Route::GetDataFromFile()
{
    vector<Route> routes;
    std::ifstream file( "routes.txt" ) ;
    char* line ;
 
    while( !file.eof() )
    {
        Route route;
 
        line = new char;
        file.getline(line, 256, '\n');
 
              route.Kotels = Kotel::GetVehiclesFromFile(line);
 
        line[strlen(line) - 4] = NULL;
 
        route.LevelOfTempWater = atoi(line);
 
        line = new char;
        file.getline(line, 256, '\n');
        route.LevelOfTempRoom = strtod(line, NULL);
 
        line = new char;
        file.getline(line, 256, '\n');
        route.LevelOfPressure = atoi(line);
 
        routes.push_back(route);
        delete [] line;
    }
 
    return routes;
}
 
void Route::SaveRoutesToFile()
{
    int i = 0;
    int j = 0;
    std::ofstream file ;
    file.open("routes.txt", ofstream::out);
    file.clear();
    
for (i = 0; i < Routes.size() - 1; i++)
    {
        file<<Routes[i].LevelOfTempWater<<endl;
        file<<Routes[i].LevelOfTempRoom<<endl;
        file<<Routes[i].LevelOfPressure<<endl;
 
        //ofstream streets;
        //char* stretsName = new char;
        //stretsName = Routes[i].NameOfKotelRoute;
        //strcat(stretsName, "-S.txt");
        //streets.open(stretsName, ofstream::out);
        //file.clear();
 
        /*for (j = 0; j < Routes[i].NamesOfStreets.size() - 1; j++)
        {
            streets<<Routes[i].NamesOfStreets[j].first<<endl;
            streets<<Routes[i].NamesOfStreets[j].second<<endl;
        }
        streets<<Routes[i].NamesOfStreets[j].first<<endl;
        streets<<Routes[i].NamesOfStreets[j].second;
        streets.close();*/
    }
    file<<Routes[i].LevelOfTempWater<<endl;
    file<<Routes[i].LevelOfTempRoom<<endl;
    file<<Routes[i].LevelOfPressure<<endl;
    file.close();
    Kotel::SaveVehiclesToFile();
}
 
void Kotel::ShowInformation()
{
    system("cls");
    cout<<"Kotels\n";
    for (int i = 0; i < Routes.size(); i++)
    {
        for (int k = 0; k < Routes[i].Kotels.size(); k++)
        {
            cout<<"\tName - "<<Routes[i].Kotels[k].NameOfKotel<<endl;
            cout<<"\tType - "<<Routes[i].Kotels[k].TypeOfKotel<<endl;
            cout<<"\tArea - "<<Routes[i].Kotels[k].AreaOfHeating<<endl;
            cout<<"\tPower[kWat] - "<<Routes[i].Kotels[k].PowerOfKotelInKwat<<endl;
            cout<<"\tPerformance - "<<Routes[i].Kotels[k].PerformanceOfHotWater<<" lt"<<endl;
            cout<<"\tPowerElectro - "<<Routes[i].Kotels[k].PowerOfElecticity<<endl<<endl;
            cout<<"\tMade in - "<<Routes[i].Kotels[k].MadeIn<<endl<<endl;
        }
        cout<<endl;
    }
}
 
vector<Kotel> Kotel::GetVehiclesFromFile(char* fileName)
{
    vector<Kotel> kotels;
 
    std::strcat(fileName, ".txt");
 
    std::ifstream file( fileName ) ;
 
    char* line ;
 
    while( !file.eof() )
    {
        Kotel kotel;
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.NameOfKotel = line;
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.TypeOfKotel = line;
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.MadeIn = line;
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.AreaOfHeating = atoi(line);
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.PowerOfKotelInKwat = atoi(line);
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.PerformanceOfHotWater = atoi(line);
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.PowerOfElecticity = atoi(line);
 
        kotels.push_back(kotel);
    }
 
    return kotels;
    delete [] line;
}
 
void Kotel::SaveVehiclesToFile()
{
    int i = 0;
    int j = 0;
    for (i = 0; i < Routes.size(); i++)
    {
        std::ofstream file;
        char* fileName = Routes[i].NameOfKotelRoute;
        strcat(fileName, ".txt");
        file.open(fileName, ofstream::out);
        file.clear();
        for (j = 0; j < Routes[i].Kotels.size() - 1; j++)
        {
            file<<Routes[i].Kotels[j].NameOfKotel<<endl;
            file<<Routes[i].Kotels[j].TypeOfKotel<<endl;
            file<<Routes[i].Kotels[j].AreaOfHeating<<endl;
            file<<Routes[i].Kotels[j].PowerOfKotelInKwat<<endl;
            file<<Routes[i].Kotels[j].PerformanceOfHotWater<<endl;
            file<<Routes[i].Kotels[j].MadeIn<<endl;
        }
        file<<Routes[i].Kotels[j].NameOfKotel<<endl;
        file<<Routes[i].Kotels[j].TypeOfKotel<<endl;
        file<<Routes[i].Kotels[j].AreaOfHeating<<endl;
        file<<Routes[i].Kotels[j].PowerOfKotelInKwat<<endl;
        file<<Routes[i].Kotels[j].PerformanceOfHotWater<<endl;
        file<<Routes[i].Kotels[j].MadeIn<<endl;
        file.close();
        //fileName = new char;
    }
}
 
void Route::ShowInformation()
{
    system("cls");
    cout<<"Routes\n";
    for (int i = 0; i < Routes.size(); i++)
    {
        cout<<"Name - "<<Routes[i].NameOfKotelRoute<<endl;
        cout<<"Temperature water - "<<Routes[i].LevelOfTempWater<<endl;
        cout<<"Temperature room - "<<Routes[i].LevelOfTempRoom<<endl;
        cout<<"Pressure - "<<Routes[i].LevelOfPressure<<" hod"<<endl;
        
        cout<<"\nVehicles:\n";
        for (int k = 0; k<Routes[i].Kotels.size(); k++)
        {
            cout<<"\tName - "<<Routes[i].Kotels[k].NameOfKotel<<endl;
            cout<<"\tType - "<<Routes[i].Kotels[k].TypeOfKotel<<endl;
            cout<<"\tArea - "<<Routes[i].Kotels[k].AreaOfHeating<<" km/hod"<<endl;
            cout<<"\tPower - "<<Routes[i].Kotels[k].PowerOfKotelInKwat<<endl;
            cout<<"\tPerformance - "<<Routes[i].Kotels[k].PerformanceOfHotWater<<" lt"<<endl;
            cout<<"\tPower - "<<Routes[i].Kotels[k].PowerOfElecticity<<endl<<endl;
            cout<<"\tMadeIn - "<<Routes[i].Kotels[k].MadeIn<<endl<<endl;
        }
        
 
cout<<endl<<endl;
    }
}
 
#pragma endregion Generic Methods
.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
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <conio.h>
#include <vector>
#include <string.h>
#include <Windows.h>
#include <time.h>
#include <process.h>
#include <Windows.h>
using namespace std;
 
#include "HeatingSystem.h"
 
#pragma region Generic Methods
 
bool ContinueOrExit()
{
    cout<<"Do you want to continue? - (y / n): ";
    int key = getch(); 
 
    if (key == 121)
    {
        return true;
    } 
    if (key == 110)
    {
        return false;
    }
}
 
#pragma endregion Generic Methods
 
int main()
{
//  srand(time(0));
 
    HeatingSystem* heatingSystem;
    Kotel kotel;
    Route route;
 
    Routes = route.GetDataFromFile();
    
    while(1)
    {
        system("cls");
        int key;
        cout<<"\n 1 - Current data\n 2 - Demonstration of the specified route within one working day\n 3 - Run simulation\n 4 - Exit\n Choose the action: ";
        cin>>key;
        switch(key)
        {
            case 1: {
 
system("cls");
int key;
cout<<"\n 1 - Transports\n 2 - Routes\n 3 - Passanger\n 4 - Exit\n Choose the action: ";
cin>>key;
switch(key)
{
        case 1:{
                heatingSystem = &kotel;
                cout<<"\n 1 - Set information\n 2 - Show information\n 3 - Exit\n Choose the action: ";
                int key;
                cin>>key;
                if (key == 1)
                {
                    heatingSystem->SetInformation();
                }
                else
                if (key == 2)
                {
                    heatingSystem->ShowInformation();
                }
                break;
               }
        case 2:{
                heatingSystem = &route;
                cout<<"\n 1 - Set information\n 2 - Show information\n 3 - Exit\n Choose the action: ";
                int key;
                cin>>key;
                if (key == 1)
                {
                    heatingSystem->SetInformation();
                }
                else
                if (key == 2)
                {
                    heatingSystem->ShowInformation();
                }
                break;
            }
//case 3:{
//              heatingSystem = &passanger;
//              cout<<"\n 1 - Change information\n 2 - Show information\n 3 - Exit\n Choose the action: ";
//              int key;
//              cin>>key;
//              if (key == 1)
//              {
//                  transportSystem->SetInformation();
//              }
//              else
//              if (key == 2)
//              {
//                  transportSystem->ShowInformation();
//              }
//              break;
//          }
case 4:{
                return 0;
            }
        }
        break;
    }
 
 
            //case 2:
            //  {
            //      //Demostrate(route);
            //      break;
            //  }
            case 3:
                {
                    for (int i = 0; i < Routes.size(); i++)
                    {
                        for (int j = 0; j < Routes[i].Kotels.size(); j++)
                        {
                            int k = (i * 10) + j;
                            //_beginthread(Simulate, 0, (void*)k);
                        }
                    }
                    break;
                }
            case 4: 
                {
                    return 0;
                }
        }
        /*if (!ContinueOrExit())
        {
            return 0;
        }*/
    }
    return 0;
}
Добавил delete [] - всеравно не помогло. VisualStudio2010.
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
03.05.2012, 23:52
Ответы с готовыми решениями:

HttpWebRequest, расход памяти непомерно больших объемов и , как следствие, утечка памяти
Добрый вечер. Мне была поставлена такая задача. Написать приложение, которая загружает из списка...

Вектор, утечка памяти, функция создания и выделение памяти
Здравствуйте. Есть проблема. функция malloc выделяет память лишь в функции CreateVector(), и при...

Утечка памяти...
Вообщем написал код: QMap&lt;QString, QMultiMap&lt;bool, QString&gt; &gt; lstPlug; QMultiMap&lt;bool,...

Утечка памяти
Привет! написал программму, и не могу разобраться где утекает память. помогите кто сможет. ...

27
Эксперт С++
8385 / 6147 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30
04.05.2012, 00:16 2
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
    char* line ;
 
    while( !file.eof() )
    {
        Kotel kotel;
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.NameOfKotel = line;
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.TypeOfKotel = line;
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.MadeIn = line;
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.AreaOfHeating = atoi(line);
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.PowerOfKotelInKwat = atoi(line);
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.PerformanceOfHotWater = atoi(line);
 
        line = new char;
        file.getline(line, 256, '\n');
        kotel.PowerOfElecticity = atoi(line);
 
        kotels.push_back(kotel);
    }
 
    return kotels;
    delete [] line;
line создается дофига раз а удаляется только один, при чем при каждом new старый указатель на выделенную память теряется...

Особо не вникал, но не вижу смысла в таком коде, как принципе и динамическом выделении памяти

Добавлено через 1 минуту
C++
1
line = new char;
Создается указатель на один символ,предпологаю что
C++
1
line = new char[256];
1
1 / 1 / 2
Регистрация: 06.11.2011
Сообщений: 68
04.05.2012, 01:20  [ТС] 3
Цитата Сообщение от Avazart Посмотреть сообщение
Создается указатель на один символ,предпологаю что
Код C++
1
line = new char[256];
Переправил на Ваш вариант, всеравно не работает программа.
0
Эксперт С++
8385 / 6147 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30
04.05.2012, 01:27 4
Вопрос зачем считывать строку, не использовав её и тут записывать следующую в ту же переменную?
0
Заблокирован
04.05.2012, 01:28 5
у чисто абстрактного класса отсутствует виртуальный диструктор
1
1 / 1 / 2
Регистрация: 06.11.2011
Сообщений: 68
04.05.2012, 22:32  [ТС] 6
Цитата Сообщение от Bers Посмотреть сообщение
у чисто абстрактного класса отсутствует виртуальный диструктор
Создал в нем чистый виртуальный деструктор - всеравно утечка памяти происходит.
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
class HeatingSystem
{
public:
    virtual void ShowInformation() = 0;
    virtual void SetInformation() = 0;
    virtual ~HeatingSystem()=0;
};
HeatingSystem::~HeatingSystem()
{}
 
class Kotel: public HeatingSystem
{
public:
    char* NameOfKotel;
    char* TypeOfKotel;
    char* MadeIn;
    int AreaOfHeating;
    int PowerOfKotelInKwat;
    int PerformanceOfHotWater;
    int PowerOfElecticity;
 
    void ShowInformation();
    void SetInformation();
    static vector<Kotel> GetVehiclesFromFile(char* fileName);
    static void SaveVehiclesToFile();
    ~Kotel() {}
 
};
 
class Route: public HeatingSystem
{
public:
    char* NameOfKotelRoute;
    int LevelOfTempWater;
    int LevelOfTempRoom;
    int LevelOfPressure;
    vector<Kotel> Kotels;
 
    void ShowInformation();
    void SetInformation();
    static vector <Route> GetDataFromFile();
    static void SaveRoutesToFile();
    ~Route() {}
};
Добавлено через 10 часов 31 минуту
Пожалуйста, покажите, что не так в программе, а то ничего не выходит.
0
Эксперт С++
8385 / 6147 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30
04.05.2012, 23:04 7
Приведите весь исправленный код, тогда будет о чем говорить...
0
1 / 1 / 2
Регистрация: 06.11.2011
Сообщений: 68
04.05.2012, 23:12  [ТС] 8
Цитата Сообщение от Avazart Посмотреть сообщение
Приведите весь исправленный код, тогда будет о чем говорить...
Пожалуйста:
.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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#pragma once
 
class HeatingSystem
{
public:
    virtual void ShowInformation() = 0;
    virtual void SetInformation() = 0;
    virtual ~HeatingSystem()=0;
};
HeatingSystem::~HeatingSystem()
{/*cout<<"Destr";*/}
 
class Kotel: public HeatingSystem
{
public:
    char* NameOfKotel;
    char* TypeOfKotel;
    char* MadeIn;
    int AreaOfHeating;
    int PowerOfKotelInKwat;
    int PerformanceOfHotWater;
    int PowerOfElecticity;
 
    void ShowInformation();
    void SetInformation();
    static vector<Kotel> GetVehiclesFromFile(char* fileName);
    static void SaveVehiclesToFile();
    ~Kotel() {}
 
};
 
class Route: public HeatingSystem
{
public:
    char* NameOfKotelRoute;
    int LevelOfTempWater;
    int LevelOfTempRoom;
    int LevelOfPressure;
    vector<Kotel> Kotels;
 
    void ShowInformation();
    void SetInformation();
    static vector <Route> GetDataFromFile();
    static void SaveRoutesToFile();
    ~Route() {}
};
 
vector<Route> Routes;
 
 
//vector <Route> Routes;
//
//vector<Kotel> FreeKotels;
 
void Kotel::SetInformation()
{
    Kotel kotel;
    cout<<"Enter the name: ";
    kotel.NameOfKotel = "";
    cin>>kotel.NameOfKotel;
 
    cout<<"Enter the type: ";
    cin>>kotel.TypeOfKotel;
 
    cout<<"Enter the area of heating: ";
    cin>>kotel.AreaOfHeating;
 
    cout<<"Enter the power of kotel in kWat: ";
    cin>>kotel.PowerOfKotelInKwat;
 
    cout<<"Enter the performance of hot water: ";
    cin>>kotel.PerformanceOfHotWater;
 
    cout<<"Enter the power of electricity: ";
    cin>>kotel.PowerOfElecticity;
 
    cout<<"Enter the country where kotel was made: ";
    cin>>kotel.MadeIn;
 
    Kotel::SaveVehiclesToFile();
}
 
void Route::SetInformation()
{
    Route route;
 
    cout<<"Enter the name: ";
    route.NameOfKotelRoute = new char;
    cin>>route.NameOfKotelRoute;
 
    cout<<"Enter the level of temperature of water: ";
    cin>>route.LevelOfTempWater;
 
    cout<<"Enter the level of temperature of room: ";
    cin>>route.LevelOfTempRoom;
 
    cout<<"Enter the pressure: ";
    cin>>route.LevelOfPressure;
 
    Routes.push_back(route);
 
    SaveRoutesToFile();
    delete [] route.NameOfKotelRoute;
}
 
#pragma region Kotel Methods
 
vector<Route> Route::GetDataFromFile()
{
    vector<Route> routes;
    std::ifstream file( "routes.txt" ) ;
    char* line ;
 
    while( !file.eof() )
    {
        Route route;
 
        line = new char[256];
        file.getline(line, 256, '\n');
 
        route.Kotels = Kotel::GetVehiclesFromFile(line);
 
        line[strlen(line) - 4] = NULL;
 
        route.LevelOfTempWater = atoi(line);
        delete [] line;
        line = new char[256];
        file.getline(line, 256, '\n');
        route.LevelOfTempRoom = strtod(line, NULL);
        delete [] line;
        line = new char[256];
        file.getline(line, 256, '\n');
        route.LevelOfPressure = atoi(line);
 
        routes.push_back(route);
        delete [] line;
    }
 
    return routes;
}
 
void Route::SaveRoutesToFile()
{
    int i = 0;
    int j = 0;
    std::ofstream file ;
    file.open("routes.txt", ofstream::out);
    file.clear();
    
for (i = 0; i < Routes.size() - 1; i++)
    {
        file<<Routes[i].LevelOfTempWater<<endl;
        file<<Routes[i].LevelOfTempRoom<<endl;
        file<<Routes[i].LevelOfPressure<<endl;
 
        //ofstream streets;
        //char* stretsName = new char;
        //stretsName = Routes[i].NameOfKotelRoute;
        //strcat(stretsName, "-S.txt");
        //streets.open(stretsName, ofstream::out);
        //file.clear();
 
        /*for (j = 0; j < Routes[i].NamesOfStreets.size() - 1; j++)
        {
            streets<<Routes[i].NamesOfStreets[j].first<<endl;
            streets<<Routes[i].NamesOfStreets[j].second<<endl;
        }
        streets<<Routes[i].NamesOfStreets[j].first<<endl;
        streets<<Routes[i].NamesOfStreets[j].second;
        streets.close();*/
    }
    file<<Routes[i].LevelOfTempWater<<endl;
    file<<Routes[i].LevelOfTempRoom<<endl;
    file<<Routes[i].LevelOfPressure<<endl;
    file.close();
    Kotel::SaveVehiclesToFile();
}
 
void Kotel::ShowInformation()
{
    system("cls");
    cout<<"Kotels\n";
    for (int i = 0; i < Routes.size(); i++)
    {
        for (int k = 0; k < Routes[i].Kotels.size(); k++)
        {
            cout<<"\tName - "<<Routes[i].Kotels[k].NameOfKotel<<endl;
            cout<<"\tType - "<<Routes[i].Kotels[k].TypeOfKotel<<endl;
            cout<<"\tArea - "<<Routes[i].Kotels[k].AreaOfHeating<<endl;
            cout<<"\tPower[kWat] - "<<Routes[i].Kotels[k].PowerOfKotelInKwat<<endl;
            cout<<"\tPerformance - "<<Routes[i].Kotels[k].PerformanceOfHotWater<<" lt"<<endl;
            cout<<"\tPowerElectro - "<<Routes[i].Kotels[k].PowerOfElecticity<<endl<<endl;
            cout<<"\tMade in - "<<Routes[i].Kotels[k].MadeIn<<endl<<endl;
        }
        cout<<endl;
    }
}
 
vector<Kotel> Kotel::GetVehiclesFromFile(char* fileName)
{
    vector<Kotel> kotels;
 
    std::strcat(fileName, ".txt");
 
    std::ifstream file( fileName ) ;
 
    char* line ;
 
    while( !file.eof() )
    {
        Kotel kotel;
 
        line = new char[256];
        file.getline(line, 256, '\n');
        kotel.NameOfKotel = line;
 
        line = new char[256];
        file.getline(line, 256, '\n');
        kotel.TypeOfKotel = line;
 
        line = new char[256];
        file.getline(line, 256, '\n');
        kotel.MadeIn = line;
 
        line = new char[256];
        file.getline(line, 256, '\n');
        kotel.AreaOfHeating = atoi(line);
 
        line = new char[256];
        file.getline(line, 256, '\n');
        kotel.PowerOfKotelInKwat = atoi(line);
 
        line = new char[256];
        file.getline(line, 256, '\n');
        kotel.PerformanceOfHotWater = atoi(line);
 
        line = new char[256];
        file.getline(line, 256, '\n');
        kotel.PowerOfElecticity = atoi(line);
 
        kotels.push_back(kotel);
    }
 
    return kotels;
    delete [] line;
}
 
void Kotel::SaveVehiclesToFile()
{
    int i = 0;
    int j = 0;
    for (i = 0; i < Routes.size(); i++)
    {
        std::ofstream file;
        char* fileName = Routes[i].NameOfKotelRoute;
        strcat(fileName, ".txt");
        file.open(fileName, ofstream::out);
        file.clear();
        for (j = 0; j < Routes[i].Kotels.size() - 1; j++)
        {
            file<<Routes[i].Kotels[j].NameOfKotel<<endl;
            file<<Routes[i].Kotels[j].TypeOfKotel<<endl;
            file<<Routes[i].Kotels[j].AreaOfHeating<<endl;
            file<<Routes[i].Kotels[j].PowerOfKotelInKwat<<endl;
            file<<Routes[i].Kotels[j].PerformanceOfHotWater<<endl;
            file<<Routes[i].Kotels[j].MadeIn<<endl;
        }
        file<<Routes[i].Kotels[j].NameOfKotel<<endl;
        file<<Routes[i].Kotels[j].TypeOfKotel<<endl;
        file<<Routes[i].Kotels[j].AreaOfHeating<<endl;
        file<<Routes[i].Kotels[j].PowerOfKotelInKwat<<endl;
        file<<Routes[i].Kotels[j].PerformanceOfHotWater<<endl;
        file<<Routes[i].Kotels[j].MadeIn<<endl;
        file.close();
        //fileName = new char;
    }
}
 
void Route::ShowInformation()
{
    system("cls");
    cout<<"Routes\n";
    for (int i = 0; i < Routes.size(); i++)
    {
        cout<<"Name - "<<Routes[i].NameOfKotelRoute<<endl;
        cout<<"Temperature water - "<<Routes[i].LevelOfTempWater<<endl;
        cout<<"Temperature room - "<<Routes[i].LevelOfTempRoom<<endl;
        cout<<"Pressure - "<<Routes[i].LevelOfPressure<<" hod"<<endl;
        
        cout<<"\nVehicles:\n";
        for (int k = 0; k<Routes[i].Kotels.size(); k++)
        {
            cout<<"\tName - "<<Routes[i].Kotels[k].NameOfKotel<<endl;
            cout<<"\tType - "<<Routes[i].Kotels[k].TypeOfKotel<<endl;
            cout<<"\tArea - "<<Routes[i].Kotels[k].AreaOfHeating<<" km/hod"<<endl;
            cout<<"\tPower - "<<Routes[i].Kotels[k].PowerOfKotelInKwat<<endl;
            cout<<"\tPerformance - "<<Routes[i].Kotels[k].PerformanceOfHotWater<<" lt"<<endl;
            cout<<"\tPower - "<<Routes[i].Kotels[k].PowerOfElecticity<<endl<<endl;
            cout<<"\tMadeIn - "<<Routes[i].Kotels[k].MadeIn<<endl<<endl;
        }
        
 
cout<<endl<<endl;
    }
}
 
#pragma endregion Generic Methods
.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
// KPIZ.cpp: определяет точку входа для консольного приложения.
//
 
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <conio.h>
#include <vector>
#include <string.h>
#include <Windows.h>
#include <time.h>
#include <process.h>
#include <Windows.h>
using namespace std;
 
#include "HeatingSystem.h"
 
#pragma region Generic Methods
 
bool ContinueOrExit()
{
    cout<<"Do you want to continue? - (y / n): ";
    int key = getch(); 
 
    if (key == 121)
    {
        return true;
    } 
    if (key == 110)
    {
        return false;
    }
}
 
#pragma endregion Generic Methods
 
int main()
{
//  srand(time(0));
 
    HeatingSystem* heatingSystem;
    Kotel kotel;
    Route route;
 
    Routes = route.GetDataFromFile();
    
    while(1)
    {
        system("cls");
        int key;
        cout<<"\n 1 - Current data\n 2 - Demonstration of the specified route within one working day\n 3 - Run simulation\n 4 - Exit\n Choose the action: ";
        cin>>key;
        switch(key)
        {
            case 1: {
 
system("cls");
int key;
cout<<"\n 1 - Transports\n 2 - Routes\n 3 - Passanger\n 4 - Exit\n Choose the action: ";
cin>>key;
switch(key)
{
        case 1:{
                heatingSystem = &kotel;
                cout<<"\n 1 - Set information\n 2 - Show information\n 3 - Exit\n Choose the action: ";
                int key;
                cin>>key;
                if (key == 1)
                {
                    heatingSystem->SetInformation();
                }
                else
                if (key == 2)
                {
                    heatingSystem->ShowInformation();
                }
                break;
               }
        case 2:{
                heatingSystem = &route;
                cout<<"\n 1 - Set information\n 2 - Show information\n 3 - Exit\n Choose the action: ";
                int key;
                cin>>key;
                if (key == 1)
                {
                    heatingSystem->SetInformation();
                }
                else
                if (key == 2)
                {
                    heatingSystem->ShowInformation();
                }
                break;
            }
//case 3:{
//              heatingSystem = &passanger;
//              cout<<"\n 1 - Change information\n 2 - Show information\n 3 - Exit\n Choose the action: ";
//              int key;
//              cin>>key;
//              if (key == 1)
//              {
//                  transportSystem->SetInformation();
//              }
//              else
//              if (key == 2)
//              {
//                  transportSystem->ShowInformation();
//              }
//              break;
//          }
case 4:{
                return 0;
            }
        }
        break;
    }
 
 
            //case 2:
            //  {
            //      //Demostrate(route);
            //      break;
            //  }
            case 3:
                {
                    for (int i = 0; i < Routes.size(); i++)
                    {
                        for (int j = 0; j < Routes[i].Kotels.size(); j++)
                        {
                            int k = (i * 10) + j;
                            //_beginthread(Simulate, 0, (void*)k);
                        }
                    }
                    break;
                }
            case 4: 
                {
                    return 0;
                }
        }
        /*if (!ContinueOrExit())
        {
            return 0;
        }*/
    }
    return 0;
}
0
Заблокирован
04.05.2012, 23:28 9
жессть вапще....

функция - одна сплошная утечка памяти. Через строчку новая утечка
vector<Kotel> Kotel::GetVehiclesFromFile(char* fileName)

Добавлено через 2 минуты
функция:
vector<Route> Route::GetDataFromFile()
Диагноз: порча памяти.

Добавлено через 1 минуту
функция:
void Route::SetInformation()
Диагноз: порча памяти

Добавлено через 1 минуту
Дальше не смотрел, ибо ножки тянуццо из порченных функций.
0
Эксперт С++
8385 / 6147 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30
04.05.2012, 23:48 10
Мдя либо читайте про динамическое выделение памяти и разбирайтесь либо
char* замениете std::string что лишит вас сложностей работы с динам.памятью и строками char-типа
1
1 / 1 / 2
Регистрация: 06.11.2011
Сообщений: 68
05.05.2012, 00:12  [ТС] 11
Цитата Сообщение от Avazart Посмотреть сообщение
char* замениете std::string что лишит вас сложностей работы с динам.памятью и строками char-типа
Вот попробовал сменить char на string, но ничего не выходит. Подскажите синтаксис:
вот одна из функций.
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
vector<Route> Route::GetDataFromFile()
{
    vector<Route> routes;
    ifstream file( "routes.txt" ) ;
    string line ;
 
    while( !file.eof() )
    {
        Route route;
 
        getline(file, line, '\n');
 
        route.Kotels = Kotel::GetVehiclesFromFile(line);
 
        //line[strlen(line) - 4] = NULL;
 
        route.LevelOfTempWater = line;
        //delete [] line;
        //line = new char[256];
        file.getline(line, 256, '\n');
        route.LevelOfTempRoom = strtod(line, NULL);
        //delete [] line;
        //line = new char[256];
        /*file.*/getline(file, line, '\n');
        route.LevelOfPressure = atoi(line);
 
        routes.push_back(route);
        //delete [] line;
    }
 
    return routes;
}
0
Эксперт С++
8385 / 6147 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30
05.05.2012, 00:16 12
Возможно
C++
1
 route.LevelOfPressure = atoi(line.c_str());
А конкретно в чем проблема?
1
1 / 1 / 2
Регистрация: 06.11.2011
Сообщений: 68
05.05.2012, 00:32  [ТС] 13
Цитата Сообщение от Avazart Посмотреть сообщение
Возможно
C++
1
 route.LevelOfPressure = atoi(line.c_str());
А конкретно в чем проблема?
Спасибо! Сейчас заменю все char на string, посмотрю, что с того выйдет.

Добавлено через 11 минут
Раньше fileName был типа char*, теперь - string. Но теперь и strcat не работает. Как исправитть ошибку?
C++
1
2
string fileName = Routes[i].NameOfKotelRoute;
        strcat(fileName, ".txt");
0
Эксперт С++
8385 / 6147 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30
05.05.2012, 01:51 14
Забыть про strcat().
std::string-строки можно склеивать с поимощью оператора сложения +
C++
1
2
3
fileName+=".txt";
fileName.append(".txt");
fileName.push_back(".txt");
Преобразовывать к chat*
C++
1
line.c_str();
Ну и другие возможности контейнера
http://www.cplusplus.com/reference/string/string/
1
1 / 1 / 2
Регистрация: 06.11.2011
Сообщений: 68
05.05.2012, 02:36  [ТС] 15
Avazart, я сменил в програме все char на string, сделал все исправления по Вашему примеру. Вот коды:
.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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#pragma once
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <conio.h>
#include <vector>
#include <string>
#include <Windows.h>
#include <time.h>
#include <process.h>
#include <Windows.h>
using namespace std;
 
class HeatingSystem
{
public:
    virtual void ShowInformation() = 0;
    virtual void SetInformation() = 0;
    virtual ~HeatingSystem();
};
HeatingSystem::~HeatingSystem()
{/*cout<<"Destr";*/}
 
class Kotel: public HeatingSystem
{
public:
    string NameOfKotel;
    string TypeOfKotel;
    string MadeIn;
    int AreaOfHeating;
    int PowerOfKotelInKwat;
    int PerformanceOfHotWater;
    int PowerOfElecticity;
 
    void ShowInformation();
    void SetInformation();
    static vector<Kotel> GetVehiclesFromFile(string fileName);
    static void SaveVehiclesToFile();
    ~Kotel() {}
 
};
 
class Route: public HeatingSystem
{
public:
    string NameOfKotelRoute;
    int LevelOfTempWater;
    int LevelOfTempRoom;
    int LevelOfPressure;
    vector<Kotel> Kotels;
 
    void ShowInformation();
    void SetInformation();
    static vector <Route> GetDataFromFile();
    static void SaveRoutesToFile();
    ~Route() {}
};
 
vector<Route> Routes;
 
 
void Kotel::SetInformation()
{
    Kotel kotel;
    cout<<"Enter the name: ";
    kotel.NameOfKotel = "";
    getline(cin, kotel.NameOfKotel);
 
    cout<<"Enter the type: ";
    cin>>kotel.TypeOfKotel;
 
    cout<<"Enter the area of heating: ";
    cin>>kotel.AreaOfHeating;
 
    cout<<"Enter the power of kotel in kWat: ";
    cin>>kotel.PowerOfKotelInKwat;
 
    cout<<"Enter the performance of hot water: ";
    cin>>kotel.PerformanceOfHotWater;
 
    cout<<"Enter the power of electricity: ";
    cin>>kotel.PowerOfElecticity;
 
    cout<<"Enter the country where kotel was made: ";
    cin>>kotel.MadeIn;
 
    Kotel::SaveVehiclesToFile();
}
 
void Route::SetInformation()
{
    Route route;
 
    cout<<"Enter the name: ";
    getline(cin, route.NameOfKotelRoute);
 
    cout<<"Enter the level of temperature of water: ";
    cin>>route.LevelOfTempWater;
 
    cout<<"Enter the level of temperature of room: ";
    cin>>route.LevelOfTempRoom;
 
    cout<<"Enter the pressure: ";
    cin>>route.LevelOfPressure;
 
    Routes.push_back(route);
 
    SaveRoutesToFile();
 
}
 
#pragma region Kotel Methods
 
vector<Route> Route::GetDataFromFile()
{
    vector<Route> routes;
    ifstream file( "routes.txt" ) ;
    string line ;
 
    while( !file.eof() )
    {
        Route route;
 
        getline(file, line, '\n');
 
        route.Kotels = Kotel::GetVehiclesFromFile(line);
 
        //line[strlen(line) - 4] = NULL;
 
        route.LevelOfTempWater = atoi(line.c_str());
        getline(file, line, '\n');
        route.LevelOfTempRoom = atoi(line.c_str());
        getline(file, line, '\n');
        route.LevelOfPressure = atoi(line.c_str());
 
        routes.push_back(route);
    }
 
    return routes;
}
 
void Route::SaveRoutesToFile()
{
    int i = 0;
    int j = 0;
    std::ofstream file ;
    file.open("routes.txt", ofstream::out);
    file.clear();
    
for (i = 0; i < Routes.size() - 1; i++)
    {
        file<<Routes[i].LevelOfTempWater<<endl;
        file<<Routes[i].LevelOfTempRoom<<endl;
        file<<Routes[i].LevelOfPressure<<endl;
 
    }
    file<<Routes[i].LevelOfTempWater<<endl;
    file<<Routes[i].LevelOfTempRoom<<endl;
    file<<Routes[i].LevelOfPressure<<endl;
    file.close();
    Kotel::SaveVehiclesToFile();
}
 
void Kotel::ShowInformation()
{
    system("cls");
    cout<<"Kotels\n";
    for (int i = 0; i < Routes.size(); i++)
    {
        for (int k = 0; k < Routes[i].Kotels.size(); k++)
        {
            cout<<"\tName - "<<Routes[i].Kotels[k].NameOfKotel<<endl;
            cout<<"\tType - "<<Routes[i].Kotels[k].TypeOfKotel<<endl;
            cout<<"\tArea - "<<Routes[i].Kotels[k].AreaOfHeating<<endl;
            cout<<"\tPower[kWat] - "<<Routes[i].Kotels[k].PowerOfKotelInKwat<<endl;
            cout<<"\tPerformance - "<<Routes[i].Kotels[k].PerformanceOfHotWater<<" lt"<<endl;
            cout<<"\tPowerElectro - "<<Routes[i].Kotels[k].PowerOfElecticity<<endl<<endl;
            cout<<"\tMade in - "<<Routes[i].Kotels[k].MadeIn<<endl<<endl;
        }
        cout<<endl;
    }
}
 
vector<Kotel> Kotel::GetVehiclesFromFile(string fileName)
{
    vector<Kotel> kotels;
 
    fileName+=".txt";
    fileName.append(".txt");
    //fileName.push_back(".txt");
 
 
    std::ifstream file( fileName ) ;
 
    string line ;
 
    while( !file.eof() )
    {
        Kotel kotel;
 
        getline(file, line, '\n');
        kotel.NameOfKotel = line;
 
        getline(file, line, '\n');
        kotel.TypeOfKotel = line;
 
        getline(file, line, '\n');
        kotel.MadeIn = line;
 
        getline(file, line, '\n');
        kotel.AreaOfHeating = atoi(line.c_str());
 
        getline(file, line, '\n');
        kotel.PowerOfKotelInKwat = atoi(line.c_str());
 
        getline(file, line, '\n');
        kotel.PerformanceOfHotWater = atoi(line.c_str());
 
        getline(file, line, '\n');
        kotel.PowerOfElecticity = atoi(line.c_str());
 
        kotels.push_back(kotel);
    }
 
    return kotels;
}
 
void Kotel::SaveVehiclesToFile()
{
    int i = 0;
    int j = 0;
    for (i = 0; i < Routes.size(); i++)
    {
        std::ofstream file;
        string fileName = Routes[i].NameOfKotelRoute;
        fileName+=".txt";
        fileName.append(".txt");
        //fileName.push_back(".txt");
 
        file.open(fileName, ofstream::out);
        file.clear();
        for (j = 0; j < Routes[i].Kotels.size() - 1; j++)
        {
            file<<Routes[i].Kotels[j].NameOfKotel<<endl;
            file<<Routes[i].Kotels[j].TypeOfKotel<<endl;
            file<<Routes[i].Kotels[j].AreaOfHeating<<endl;
            file<<Routes[i].Kotels[j].PowerOfKotelInKwat<<endl;
            file<<Routes[i].Kotels[j].PerformanceOfHotWater<<endl;
            file<<Routes[i].Kotels[j].MadeIn<<endl;
        }
        file<<Routes[i].Kotels[j].NameOfKotel<<endl;
        file<<Routes[i].Kotels[j].TypeOfKotel<<endl;
        file<<Routes[i].Kotels[j].AreaOfHeating<<endl;
        file<<Routes[i].Kotels[j].PowerOfKotelInKwat<<endl;
        file<<Routes[i].Kotels[j].PerformanceOfHotWater<<endl;
        file<<Routes[i].Kotels[j].MadeIn<<endl;
        file.close();
        //fileName = new char;
    }
}
 
void Route::ShowInformation()
{
    system("cls");
    cout<<"Routes\n";
    for (int i = 0; i < Routes.size(); i++)
    {
        cout<<"Name - "<<Routes[i].NameOfKotelRoute<<endl;
        cout<<"Temperature water - "<<Routes[i].LevelOfTempWater<<endl;
        cout<<"Temperature room - "<<Routes[i].LevelOfTempRoom<<endl;
        cout<<"Pressure - "<<Routes[i].LevelOfPressure<<" hod"<<endl;
        
        cout<<"\nVehicles:\n";
        for (int k = 0; k<Routes[i].Kotels.size(); k++)
        {
            cout<<"\tName - "<<Routes[i].Kotels[k].NameOfKotel<<endl;
            cout<<"\tType - "<<Routes[i].Kotels[k].TypeOfKotel<<endl;
            cout<<"\tArea - "<<Routes[i].Kotels[k].AreaOfHeating<<" km/hod"<<endl;
            cout<<"\tPower - "<<Routes[i].Kotels[k].PowerOfKotelInKwat<<endl;
            cout<<"\tPerformance - "<<Routes[i].Kotels[k].PerformanceOfHotWater<<" lt"<<endl;
            cout<<"\tPower - "<<Routes[i].Kotels[k].PowerOfElecticity<<endl<<endl;
            cout<<"\tMadeIn - "<<Routes[i].Kotels[k].MadeIn<<endl<<endl;
        }
        
 
cout<<endl<<endl;
    }
}
 
#pragma endregion Generic Methods
.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
// KPIZ.cpp: определяет точку входа для консольного приложения.
//
 
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <conio.h>
#include <vector>
#include <string.h>
#include <Windows.h>
#include <time.h>
#include <process.h>
#include <Windows.h>
using namespace std;
 
#include "HeatingSystem.h"
 
#pragma region Generic Methods
 
//bool ContinueOrExit()
//{
//  cout<<"Do you want to continue? - (y / n): ";
//  int key = getch(); 
//
//  if (key == 121)
//  {
//      return true;
//  } 
//  if (key == 110)
//  {
//      return false;
//  }
//}
 
#pragma endregion Generic Methods
 
int main()
{
    srand(time(0));
 
    HeatingSystem* heatingSystem;
    Kotel kotel;
    Route route;
 
    Routes = route.GetDataFromFile();
    
    while(1)
    {
        system("cls");
        int key;
        cout<<"\n 1 - Current data\n 2 - Demonstration of the specified route within one working day\n 3 - Run simulation\n 4 - Exit\n Choose the action: ";
        cin>>key;
        switch(key)
        {
            case 1: {
 
system("cls");
int key;
cout<<"\n 1 - Transports\n 2 - Routes\n 3 - Passanger\n 4 - Exit\n Choose the action: ";
cin>>key;
switch(key)
{
        case 1:{
                heatingSystem = &kotel;
                cout<<"\n 1 - Set information\n 2 - Show information\n 3 - Exit\n Choose the action: ";
                int key;
                cin>>key;
                if (key == 1)
                {
                    heatingSystem->SetInformation();
                }
                else
                if (key == 2)
                {
                    heatingSystem->ShowInformation();
                }
                break;
               }
        case 2:{
                heatingSystem = &route;
                cout<<"\n 1 - Set information\n 2 - Show information\n 3 - Exit\n Choose the action: ";
                int key;
                cin>>key;
                if (key == 1)
                {
                    heatingSystem->SetInformation();
                }
                else
                if (key == 2)
                {
                    heatingSystem->ShowInformation();
                }
                break;
            }
 
case 4:{
                return 0;
            }
        }
        break;
    }
 
 
 
            case 3:
                {
                    for (int i = 0; i < Routes.size(); i++)
                    {
                        for (int j = 0; j < Routes[i].Kotels.size(); j++)
                        {
                            int k = (i * 10) + j;
                            //_beginthread(Simulate, 0, (void*)k);
                        }
                    }
                    break;
                }
            case 4: 
                {
                    return 0;
                }
        }
        /*if (!ContinueOrExit())
        {
            return 0;
        }*/
    }
    return 0;
}
Утечка памяти присутствует, но идет очень медленно. Программа по прежнему не работает - черная консоль.
Запустил дебагер, видал вот такую картину. Скорее всего, дело в виртуальном деструкторе.
Утечка памяти (Expression: _CrtIsValidHeapPointer(pUserData))

Возможно как-то все-таки запустить программу, чтоб она смогла нормально заработать?
P.S. Большое спасибо за то, что помогаете.
0
Эксперт С++
8385 / 6147 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30
05.05.2012, 05:06 16
Утечка памяти присутствует, но идет очень медленно. Программа по прежнему не работает - черная консоль.
Запустил дебагер, видал вот такую картину. Скорее всего, дело в виртуальном деструкторе.
Откуда утечки взятся если вы не выделяете память динамически?
И если вы не не выделяете память динамически то деструкторы нафиг не нужны потому как освобождать нечего.

Добавлено через 4 минуты
Хотя я не особо понимаю строки
C++
1
2
HeatingSystem* heatingSystem;
Kotel kotel;
И с
C++
1
heatingSystem = &kotel;
Добавлено через 3 минуты
C++
1
fileName+=".txt";
C++
1
fileName.append(".txt");
C++
1
fileName.push_back(".txt");
Это три варианта одного и того же действия, добавить в конец строки ".txt"
Это ошибка в строке 190
1
Заблокирован
05.05.2012, 21:00 17
Цитата Сообщение от Avazart Посмотреть сообщение
И если вы не не выделяете память динамически то деструкторы нафиг не нужны потому как освобождать нечего.
Деструкторы не просто нужны. Они в принципе нужны. Без деструктора вся приплюснутая ОО-архитектура сразу же пойдёт крахом. Этим объясняется тот факт, что если программист сам не укажет деструктор, то за него его автоматически сгенерирует компилятор.

Но есть нюансы: компилятор не всегда способен создать деструктор корректно. Это связано с сложностями парсинга кода на с++. В результате:

Смотри:

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef Test_h
#define Test_h
 
#include <iostream>
struct test2
{
    ~test2() { std::cout <<"dtor\n";  }  //по факту вызван не будет
};
 
class Test
{
public:
    void Work();
    test2 tmp;    //мембер не будет корректно разрушен. Утечка ресурсов
};
 
#endif
C++
1
: warning C4150: удаление указателя на неполный тип 'Test'; деструктор не вызван
Причем, по стандарту компиляторы не обязаны пасти такую ситуацию. Это называется "хорошо отделался", если хотя бы варнинг получил. А вот под линуксом QtCreator даже ухом не повел. Если бы под винду не начали портировать - и знать бы не знали, что у нас ресы утекают.

На месте тестовой болванки может оказаться какой нибудь вектор, или ещё что нибудь этакое.
У них не будет вызван деструктор, и они не освободят захваченные ресурсы.

И ладно, если это просто утечка памяти, а если там какие то особо важные ресурсы были под контролем?

А все потому, что человек поленился один раз написать явный деструктор (пусть даже пустой).

/зы: взял себе за правило: всегда писать явный дестурктор, и не иметь проблем.
0
Эксперт С++
8385 / 6147 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30
05.05.2012, 21:22 18
Builder справляется с предложеным кодом
Миниатюры
Утечка памяти (Expression: _CrtIsValidHeapPointer(pUserData))  
0
Заблокирован
05.05.2012, 21:31 19
Цитата Сообщение от Avazart Посмотреть сообщение
Builder справляется с предложеным кодом
С теми двумя тестовыми классами в сферическом вакууме все в полном порядке))

Проблемы начинаются в многофайловом проекте. А если там ещё и иерархия очень развитая - там вообще без 100 грамм потом не разберёшься.

Попробуй протестировать вот такую вещь:

Предположим, что данный класс - один из многих в большой-большой системе:

//CAgent.h
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#ifndef CAgent_h
#define CAgent_h
 
//интеллектуальный шаристый указатель.
#include "ConstCode/Template/TSharedPointer.h"
 
class Test;
typedef TSharedPointer< Test > pTest_t;
 
class Agent
{
public:
    Agent();
    ~Agent();
    pTest_t GetTest()const;   
private:
    pTest_t mpTest;  //наш подопытный кролик
};
 
#endif
//CAgent.cpp
C++ (Qt)
1
2
3
4
5
#include "Test.h"
 
Agent::Agent(){ mpTest = new Test();}
Agent::~Agent(){}
pTest_t Agent::GetTest()const{ return mpTest; }
//Test.h

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef Test_h
#define Test_h
 
#include <iostream>
struct test2
{
    ~test2() { std::cout <<"dtor\n";  }
};
 
class Test
{
public:
    void Work();
    test2 tmp;
};
#endif
//main.cpp
C++ (Qt)
1
2
3
4
5
6
7
int main()
{
    Agent agent;
 
    pTest_t gm; 
    gm = agent.GetTest(); 
}

Собственно, попадаем во внутрь интеллектуального указателя:


C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
void_TSharedPointer::Release() 
{   
    if(mp_CounterLink==0)  { return; }
    --(*mp_CounterLink);
    if( (*mp_CounterLink)==0 ) 
    { 
    //: warning C4150: удаление указателя на неполный тип 'Test'; деструктор не вызван
        delete mp_CounterLink; delete mp_Pointer; 
    }
    Clear();
}
Справедливости ради, стоит заметить, что в бустовских умных указателях учли этот нюанс. Там стоит защита. Если нечто подобное будет иметь место быть - будет ошибка времени компиляции, но я сам не проверял.
0
Эксперт С++
8385 / 6147 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30
05.05.2012, 21:49 20
Qt Creator под Win7 тоже кстати норм работает предыдущем кодом
Миниатюры
Утечка памяти (Expression: _CrtIsValidHeapPointer(pUserData))  
0
05.05.2012, 21:49
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
05.05.2012, 21:49
Помогаю со студенческими работами здесь

утечка памяти
если запустить код char *pointer = NULL; for( int i = 0; i &lt; 10; i++ ) { pointer = new char; }...

Утечка памяти
Здравствуйте. Навоял такой вот кодик. Когда много файлов в директории dir, происходит утечка...

Утечка памяти
Почему даже в пустом приложении, в котором весь код(кроме main) сгенерировала сама среда, идут...

Утечка памяти
Сворачиваю приложение в трей, затем убираю значок с панели задач, и тут начинается утечка памяти,...


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

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

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