Как убрать ошибку выделение памяти в С90
Компилятор выдал Process returned -1073741819 (0xC0000005), если не ставить настройки в gnu gcc compiler такие как на фото
Это настройки в компиляторе Code::Blocks, в Clion если ставить проект C90, та же ошибка.
Читал данные из файла data.txt c таким по формату содержанием для занесения в линейный односвязный список
Chevrolet Aveo (T250);Chevrolet;500;6;1568.6;350.12;20;45;75;90;120;180;
Skoda Kamiq;Skoda;1000;6;1570.5;6450;15;30;55;80;110;200;
Honda Ridgeline;Honda;1500;6;2000;17887.5;20;40;80;120;150;180;
Lexus NX;Lexus;750;5;2265.23;82812.5;30;60;80;120;200;*
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct cars {
int id; //ID
char *name;// потом динамически выделяется память под имя
char *producer;// та же песня
int max_load;//макс нагрузка
int count_gears;//кол-во передач
float weight;//вес
float price;//цена
int *max_speed_grear;//массив с макс скоростями для каждой передачи
struct cars *next;//указатель на следующий элемент списка
} cr;
typedef struct head {
int count;//количество элементов всего
cr *first;//указатель на первый элемент списка
cr *last;//на последний элемент список
} head;
head *make_head() {
head *ph = NULL;
ph = (head*)malloc(sizeof(head));
if (ph) {
ph->count = 0;
ph->first = NULL;
ph->last = NULL;
}
return ph;
}
void read_file(head* ph, char* filename) {
int i;
FILE *file;
file = fopen(filename, "r");
if (!file) {
printf("File not found\n");
return;
}
char line[256];
while (fgets(line, sizeof(line), file)) {
cr* car = (cr*)malloc(sizeof(cr));
if (!car) {
printf("Memory allocation error\n");
return;
}
char* pos = line;
char* end;
car->name = (char*)malloc(sizeof(char) * 256);
if (!car->name) {
printf("Memory allocation error\n");
return;
}
end = strchr(pos, ';');
strncpy(car->name, pos, end - pos);
car->name[end - pos] = '\0';
pos = end + 1;
car->producer = (char*)malloc(sizeof(char) * 256);
if (!car->producer) {
printf("Memory allocation error\n");
return;
}
end = strchr(pos, ';');
strncpy(car->producer, pos, end - pos);
car->producer[end - pos] = '\0';
pos = end + 1;
car->max_load = strtol(pos, &end, 10);
pos = end + 1;
car->count_gears = strtol(pos, &end, 10);
pos = end + 1;
car->weight = strtof(pos, &end);
pos = end + 1;
car->price = strtof(pos, &end);
pos = end + 1;
car->max_speed_grear = (int*)malloc(sizeof(int) * car->count_gears);
if (!car->max_speed_grear) {
printf("Memory allocation error\n");
return;
}
for (i = 0; i < car->count_gears; i++) {
car->max_speed_grear[i] = strtol(pos, &end, 10);
pos = end + 1;
}
car->next = NULL;
if (!ph->first) {
ph->first = car;
ph->last = car;
} else {
ph->last->next = car;
ph->last = car;
}
ph->count++;
}
fclose(file);
}
void print_cars(head* ph)
{
cr* curr = ph->first;
int i = 1, j;
printf("No. | Car name | Car manufacturer | Maximum load, kg | Count gears | Price, USD | Maximum speed in each gear\n");
printf("----|--------------------------|----------------------|------------------|-------------|-------------|--------------------------------------------------------\n");
while (curr) {
char car_str[200];
int k = 0;
k += snprintf(car_str + k, sizeof(car_str) - k, "%-4d| %-25s| %-21s| %-16d| %-12d| %-12.2f| ", i, curr->name, curr->producer, curr->max_load, curr->count_gears, curr->price);
for (j = 0; j < curr->count_gears; j++)
k += snprintf(car_str + k, sizeof(car_str) - k, "%d ", curr->max_speed_grear[j]);
printf("%s\n", car_str);
curr = curr->next;
i++;
}
}
void remove_by_index(head* ph, int index)
{ cr* prev;
cr* curr;
int i;
if (index < 1 || index > ph->count) {
printf("Invalid index\n");
return;
}
prev = NULL;
curr = ph->first;
i = 1;
while (curr != NULL && i != index) {
prev = curr;
curr = curr->next;
i++;
}
if (curr == NULL) {
printf("Element not found.\n");
return;
}
if (prev == NULL) {
ph->first = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
ph->count--;
}
void reverse_list(head* ph) {
cr* prev = NULL;
cr* curr = ph->first;
cr* next = NULL;
while (curr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
ph->last = ph->first;
ph->first = prev;
}
int main() {
head* ph;
int index, from_end;
ph = make_head();
read_file(ph, "data.txt");
print_cars(ph);
printf("Enter the number of the element, counting from the end, that you want to remove:\n");
scanf("%d", &from_end);
index = ph->count - from_end + 1;
if (index < 1 || index > ph->count) {
printf("Invalid index\n");
} else {
printf("\nAfter remove:\n");
remove_by_index(ph, index);
print_cars(ph);
}
reverse_list(ph);
printf("\nAfter reverse:\n");
print_cars(ph);
return 0;
}
Можно попытаться потом очищать память ,изменив main, но это погоды не изменит
int main() {
head* ph;
int index, from_end;
ph = make_head();
read_file(ph, "cars.txt");
print_cars(ph);
//удаление элемента списка
printf("Enter the index of the element to be removed: ");
scanf("%d", &index);
remove_by_index(ph, index);
print_cars(ph);
//инвертирование списка
reverse_list(ph);
print_cars(ph);
//очистка памяти
cr* curr = ph->first;
cr* temp;
while (curr) {
temp = curr;
curr = curr->next;
free(temp->name);
free(temp->producer);
free(temp->max_speed_grear);
free(temp);
}
free(ph);
return 0;
}