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

Ошибка при удалении элемента из динамической памяти

07.05.2022, 16:45. Показов 337. Ответов 2
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Здравствуйте. Нужно реализовать удаление определенной машины. Прописала функцию удаления, но выдает ошибку после удаления и попытки вывести все машины на экран. Помогите разобраться пожалуйста.

Ошибка при удалении элемента из динамической памяти


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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
#include<iostream>
#include<time.h>
using namespace std;
 
struct car {
    char brend[30];
    char model[30];
    char number[30];
    char color[30];
    int year;
    int price;
};
 
struct user {
    char name[50];
    char surname[50];
    char fathersname[50];
    char car[50];
    short firstday;
    short firstmonth;
    short lastday;
    short lastmonth;
};
void show_cars(car cars);
void show_users(user users);
car* addcar(car*& cars, int& size);
user* adduser(user*& users, int& size);
void menu();
void choose(car* cars, user* users, int& size, int&size1);
void carsearch(car cars[], int size);
void contractsearch(user users[], int size1);
void backmenu();
int monthdays(int month);
void carsearch_brend(car* cars, int& size);
void carsearch_price(car* cars, int& size);
void carsearch_number(car* cars, int& size);
void carsearch_color(car* cars, int& size);
void carsearch_year(car* cars, int& size);
void contractsearch_name(user users[], int size1);
void contractsearch_surname(user users[], int size1);
void contractsearch_fathersname(user users[], int size1);
car* dellcar(car*& cars, int& size);
user* delluser(user*& users, int& size1);
void dellall(car*& cars, user*& users, int& size, int& size1);
void debt(user* users, int& size1);
 
int main() {
    int size = 20;
    int* ptr_size = new int[size];
    car* cars = new car[size]{
        { "Toyota", "Prado", "90-JM-122", "White", 2019, 200},
        {"Toyota", "Prius", "90-JM-250", "Red", 2017, 60},
        {"Toyota", "Rav4", "90-JM-100", "Black", 2022, 200},
        {"Toyota", "Camry", "90-JM-155", "Green", 2014, 150},
        {"Toyota", "Corolla", "90-JM-145", "Purple", 2006, 50},
        {"BMW", "X4", "96-JM-096", "Black", 2016, 300},
        {"BMW", "X5", "96-JM-010", "White", 2006, 150},
        {"BMW", "X6", "96-JM-096", "Blue", 2022, 550},
        {"Chevrolet", "Malibu", "91-JM-556","Yellow", 2016, 70},
        {"Dodge", "Challenger", "92-JM-298", "Blue", 2019, 350},
        {"Ferrari", "Portofino", "99-JM-099", "Red", 2017, 3000},
        {"Ferrari", "California", "99-JM-199", "Red", 2014, 2850},
        {"Audi", "R8", "98-JM-009", "Grey", 2010, 1450},
        {"Hundai", "Elantra", "95-JM-378", "Yellow", 2021, 250},
        {"Hundai", "Sonata", "95-JM-561", "Brown", 2015, 120},
        {"Honda", "CR-V", "95-JM-567", "Violet", 2000, 50},
        {"Kia", "Rio", "93-JM-019", "Green", 2006, 60},
        {"Mersedes", "E-220", "97-JM-119", "Black", 2011, 120},
        {"Nissan", "Sunny", "92-JM-666", "Purple", 2014, 100},
        {"Opel", "Astra", "94-JM-789", "Grey", 2015, 80} 
    };
    int size1 = 10;
    int* ptr_size1 = new int[size1];
    user* users = new user[size1]{
        {"Jala", "Mukhamedova", "Mirza", "Prado", 20, 4, 25, 4},
        {"Oguz", "Mustayev", "Vugar", "Prius", 15, 5, 25, 5},
        {"Gulnara", "Mukhamedova", "Mahmud", "Portofino", 5, 3, 25, 3},
        {"Ali", "Abdullayev", "Heydar", "California", 20, 4, 25, 4},
        {"Aygun", "Mukhtarova", "Mamed", "Sunny", 7, 4, 10, 4},
        {"Baloglan", "Balabanov", "Gelemder", "Malibu", 9, 8, 19, 9},
        {"Abbas", "Eyvazov", "Aliyar", "CR-V", 3, 4, 23, 4},
        {"Cahangir", "Zeynalov", "Elshen", "Astra", 11, 2, 20, 2},
        {"Gunay", "Aliyeva", "Arzu", "Elantra", 17, 5, 20, 5},
        {"Aliyar", "Hesenov", "Hamid", "E-220", 13, 2, 27, 2},
    };
 
    menu();
    choose(cars, users, size, size1);
 
}
 
 
 
void show_cars(car cars){
    cout << "Brend: \t" << cars.brend << endl;
    cout << "Model: \t\t" << cars.model << endl;
    cout << "Number:\t\t" << cars.number << endl;
    cout << "Color:\t\t" << cars.color << endl;
    cout << "Year:\t\t" << cars.year << endl;
    cout << "Price(in manats):" << cars.price << endl;
    cout << "____________________________________" << endl;
}
void show_users(user users) {
    cout << "Name:\t\t" << users.name << endl;
    cout << "Surname:\t" << users.surname << endl;
    cout << "Fathers Name: \t" << users.fathersname << endl;
    cout << "Arended Car:\t" << users.car << endl;
    cout << "Rental Date:\t" << users.firstday<<"."<<users.firstmonth << endl;
    cout << "Return Date:\t" << users.lastday<<"."<<users.lastmonth << endl;
    cout << "____________________________________" << endl;
}
void backmenu() {
    int rep;
    cout << "Back to menu?(1-Yes, 2-No): ";
    cin >> rep;
    if (rep == 1) {
        system("cls");
        menu();
    }
    else {
        system("pause");
    }
}
void menu() {
    cout << "\t\tWelcome to 'MUKHAMEDOFF`S RENT A CAR' company" << endl;
    cout << "1.Watch all cars" << endl;
    cout << "2.Watch all contracts" << endl;
    cout << "3.Search car" << endl;
    cout << "4.Search contract" << endl;
    cout << "5.Add car" << endl;
    cout << "6.Add contract" << endl;
    cout << "7.Customer debt" << endl;
    cout << "8.Delete contract" << endl;
    cout << "9.Delete car" << endl;
    cout << "10.Delete All" << endl;
    cout << "_____________________________" << endl;
}
int monthdays(int month) {
    switch (month)
    {
    case 1:
        return 31;
        break;
    case 2:
        return 28;
        break;
    case 3:
        return 31;
        break;
    case 4:
        return 30;
        break;
    case 5:
        return 31;
        break;
    case 6:
        return 30;
        break;
    case 7:
        return 31;
        break;
    case 8:
        return 31;
        break;
    case 9:
        return 30;
        break;
    case 10:
        return 31;
        break;
    case 11:
        return 30;
        break;
    case 12:
        return 31;
        break;
    default:
        break;
    }
}
car* addcar(car*& cars, int& size) {
    car* tmp = new car[size];
    for (int i = 0; i < size; i++) {
        tmp[i] = cars[i];
    }
 
    cout << "You are adding new car, be careful!" << endl;
    cout << "The brend: ";
    cin >> tmp[size].brend;
    cout << "The model: ";
    cin >> tmp[size].model;
    cout << "Color: ";
    cin >> tmp[size].color;
    cout << "Number: ";
    cin >> tmp[size].number;
    cout << "Year: ";
    cin >> tmp[size].year;
    cout << "Price per day(in manats): ";
    cin >> tmp[size].price;
    delete[]cars;
    size++;
    return tmp;
}
user* adduser(user*& users, int& size1) {
    user* tmp = new user[size1];
    for (int i = 0; i < size1; i++) {
        tmp[i] = users[i];
    }
 
    cout << "You are adding new contract, be careful!" << endl;
    cout << "Name: ";
    cin >> tmp[size1].name;
    cout << "Surname: ";
    cin >> tmp[size1].surname;
    cout << "Father`s name: ";
    cin >> tmp[size1].fathersname;
    cout << "Write the day and month of rental date (for example 4 12): ";
    cin >> tmp[size1].firstday >> tmp[size1].firstmonth;
    cout << "Write the day and month of return date (for example 4 12):";
    cin >> tmp[size1].lastday >> tmp[size1].lastmonth;
    delete[]users;
    size1++;
    return tmp;
}
car* dellcar(car*& cars, int& size) {
    car* tmp = new car[size];
    char fin[30];
    for (int i = 0; i < size; i++) {
        cout << cars[i].brend << " " << cars[i].model << " " << cars[i].number << endl;
    }
    cout << "You are deleting car, be careful!" << endl;
    cout << "Write the number of car(example 92-JM-092): ";
    cin >> fin;
    for (int i = 0; i < size; i++) {
        if (strcmp(fin, cars[i].number) != 0) {
            tmp[i] = cars[i];
        }
    }
    delete[]cars;
    size--;
    return tmp;
}
user* delluser(user*& users, int& size1) {
    user* tmp = new user[size1];
    char fin[30];
    char fin1[30];
    for (int i = 0; i < size1; i++) {
        cout << users[i].name << " " << users[i].surname << " " << users[i].fathersname << endl;
    }
    cout << "You are deleting a contract, be careful!" << endl;
    cout << "Write the customers name: ";
    cin >> fin;
    cout << "Write the customers surname: ";
    cin >> fin1;
    for (int i = 0; i < size1; i++) {
        if (strcmp(fin, users[i].name) != 0||strcmp(fin1, users[i].surname)!=0) {
            tmp[i] = users[i];
        }
    }
    delete[]users;
    size1--;
    return tmp;
}
//void dellall(car*& cars, user*& users, int& size, int& size1) {
//  car* tmp1 = new car  [size];
//  user* tmp2 = new user[size1];
//  delete[]cars;
//  delete[]users;
//
//}
void carsearch_brend(car* cars, int& size){
    char find[30];
    bool finded = false;
    cout << "Enter the brend: ";
    cin >> find;
    for (int i = 0; i < size; i++) {
        if (strcmp(find, cars[i].brend) == 0) {
            show_cars(cars[i]);
            finded = true;
        }
    }
    if (finded == false) {
        cout << "There is no matches!" << endl;
    }
}
void carsearch_number(car* cars, int& size) {
    char find[30];
    bool finded = false;
    cout << "Enter the number: ";
    cin >> find;
    for (int i = 0; i < size; i++) {
        if (strcmp(find, cars[i].number) == 0) {
            show_cars(cars[i]);
            finded = true;
        }
    }
    if (finded == false) {
        cout << "There is no matches!" << endl;
    }
}
void carsearch_color(car* cars, int& size) {
    char find[30];
    bool finded = false;
    cout << "Enter the color: ";
    cin >> find;
    for (int i = 0; i < size; i++) {
        if (strcmp(find, cars[i].color) == 0) {
            show_cars(cars[i]);
            finded = true;
        }
    }
    if (finded == false) {
        cout << "There is no matches!" << endl;
    }
}
void carsearch_year(car* cars, int& size) {
    int find;
    bool finded = false;
    cout << "Enter the year: ";
    cin >> find;
    for (int i = 0; i < size; i++) {
        if (find == cars[i].year) {
            show_cars(cars[i]);
            finded = true;
        }
    }
    if (finded == false) {
        cout << "There is no matches!" << endl;
    }
}
void carsearch_price(car* cars, int& size) {
    int find1, find2;
    bool finded = false;
    cout << "Enter the start and end of price(example 50 100): ";
    cin >> find1 >> find2;
    for (int i = 0; i < size; i++) {
        if (cars[i].price >= find1& cars[i].price <= find2) {
            show_cars(cars[i]);
            finded = true;
        }
    }
    if (finded == false) {
        cout << "There is no matches!" << endl;
    }
}
void carsearch(car cars[], int size) {
    system("cls");
    int item;
    cout << "1. Search by brend" << endl;
    cout << "2. Search by number" << endl;
    cout << "3. Search by color" << endl;
    cout << "4. Search by year" << endl;
    cout << "5. Search by price" << endl;
    cout << "Choose the item(1-by model...etc): " << endl;
    cin >> item;
    system("cls");
    switch (item) {
    case 1:
        carsearch_brend(cars, size);
        break;
    case 2:
        carsearch_number(cars, size);
        break;
    case 3:
        carsearch_color(cars, size);
        break;
    case 4:
        carsearch_year(cars, size);
        break;
    case 5:
        carsearch_price(cars, size);
        break;
    }
}
void contractsearch_name(user users[], int size1) {
    char find[30];
    bool finded = false;
    cout << "Enter the name: ";
    cin >> find;
    for (int i = 0; i < size1; i++) {
        if (strcmp(find, users[i].name) == 0) {
            show_users(users[i]);
            finded = true;
        }
    }
    if (finded == false) {
        cout << "There is no matches!" << endl;
    }
}
void contractsearch_surname(user users[], int size1) {
    char find[30];
    bool finded = false;
    cout << "Enter the surname: ";
    cin >> find;
    for (int i = 0; i < size1; i++) {
        if (strcmp(find, users[i].surname) == 0) {
            show_users(users[i]);
            finded = true;
        }
    }
    if (finded == false) {
        cout << "There is no matches!" << endl;
    }
}
void contractsearch_fathersname(user users[], int size1) {
    char find[30];
    bool finded = false;
    cout << "Enter the father`s name: ";
    cin >> find;
    for (int i = 0; i < size1; i++) {
        if (strcmp(find, users[i].fathersname) == 0) {
            show_users(users[i]);
            finded = true;
        }
    }
    if (finded == false) {
        cout << "There is no matches!" << endl;
    }
}
void contractsearch(user users[], int size1) {
    system("cls");
    int item;
    cout << "1. Search by name" << endl;
    cout << "2. Search by surname" << endl;
    cout << "3. Search by father`s name" << endl;
    cout << "Choose the item(1-by model...etc): " << endl;
    cin >> item;
    system("cls");
    switch (item) {
    case 1:
        contractsearch_name(users, size1);
        break;
    case 2:
        contractsearch_surname(users, size1);
        break;
    case 3:
        contractsearch_fathersname(users, size1);
        break;
    }
}
void debt(user* users, int& size1) {
    char name[30];
    char surname[30];
    int day_diff, act_day, act_month, month;
    cout << "Write the name of user:";
    cin>>name;
    cout << "Write the surname of user;";
    cin>>surname;
    cout << "Write the actual date(example 4 12 for 4th of december): ";
    cin >> act_day >> act_month;
 
    for (int i = 0; i < size1; i++) {
        if (strcmp(name, users[i].name)==0 && strcmp(surname, users[i].surname)==0) {
            month = monthdays(users[i].firstmonth);
        }
    }
}
void choose(car* cars, user* users, int& size, int&size1) {
    int item;
    cout << "Choose the item(1-all cars...etc): " << endl;
    cin >> item;
    system("cls");
    switch (item)
    {
    case 1:
        for (int i = 0; i < size; i++) {
            show_cars(cars[i]);
        }break;
    case 2:
        for (int i = 0; i < size1; i++) {
            show_users(users[i]);
        }break;
    case 3:
        system("cls");
        carsearch(cars, size);
        break;
 
    case 4:
        system("cls");
        contractsearch(users, size1);
        break;
    case 5:
        cars = addcar(cars, size);
        cout << "Car sucsessfully added!" << endl;
        break;
    case 6:
        users = adduser(users, size);
        cout << "Contract sucsessfully added!" << endl;
        break;
    case 7:
        break;
    case 8:
        delluser(users, size1);
        break;
    case 9:
        dellcar(cars, size);
        break;
    /*case 10:
        dellall(cars, users, size, size1);
        break;*/
    }
    backmenu();
    choose(cars, users, size, size1);
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
07.05.2022, 16:45
Ответы с готовыми решениями:

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

Освобождение памяти при удалении элемента в List<T>
Доброго времени суток, уважаемые форумчане! Скажите пожалуйста, если присвоить значение элементу...

Ошибка при удалении памяти
Кто подскажет, почему на удалении указателей программа выдает срабатывание точки останова? Что не...

Ошибка при удалении динамически выделенной памяти
Добрый день, хочу удалить выделенный массив, но выдает ошибку. Вот собственно код создаваемой...

2
Модератор
Эксперт С++
13507 / 10757 / 6412
Регистрация: 18.12.2011
Сообщений: 28,712
07.05.2022, 17:12 2
Цитата Сообщение от Actaeon Посмотреть сообщение
ser* adduser(user*& users, int& size1) {
user* tmp = new user[size1];
Нужно на 1 больше
C++
1
user* tmp = new user[size1+1];
Цитата Сообщение от Actaeon Посмотреть сообщение
for (int i = 0; i < size; i++) {
if (strcmp(fin, cars[i].number) != 0) {
tmp[i] = cars[i];
}
}
для tmp нужен отдельный счетчик
C++
1
2
3
4
5
6
7
8
9
int j=0;
for (int i = 0; i < size; i++) {
    if (strcmp(fin, cars[i].number) != 0) {
       tmp[j++] = cars[i];  // !!!!!!!!!!!!!!!!!!!!!!!!!
    }
}
delete[]cars;
size=j;  //  !!!!!!!!!!!!!!!!!!!!!!
return tmp;
Аналогично для user
0
0 / 0 / 0
Регистрация: 27.09.2021
Сообщений: 21
07.05.2022, 17:25  [ТС] 3
исправила. выводит ту же самую ошибку
0
07.05.2022, 17:25
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
07.05.2022, 17:25
Помогаю со студенческими работами здесь

Ошибка с delete при удалении памяти из-под строки
strngbad.h // strngbad.h -- flawed string class definition #include &lt;iostream&gt; #ifndef...

Ошибка при удалении элемента (STL)
У меня есть вектор списков. Мне нужно во внутреннем цикле(в списке) удалить элемент. Ошибка...

Ошибка при удалении единственного элемента
Помогите найти и исправить ошибку. Есть код public void Delete(Tkey key) { ...

Ошибка при удалении первого элемента
Здравствуйте! Столкнулся с такой проблемой: ниже код кнопки удаления. Все работает при удалении...

Ошибка при удалении первого элемента
Здравствуйте! Столкнулся с такой проблемой: ниже код кнопки удаления. Все работает при удалении...

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

Ошибка при освобождении динамической памяти
Выдает такую вот ошибку при вызове деструктора: HEAP CORRUPTION DETECTED: after Normal block...


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

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