У меня есть эта программа, которая читает целые числа, которые соответствуют узлам и ребрам, пропуская строки, начинающиеся с #. Я пытаюсь создать массив, который хранит группу отсортированных узлов (так называемый словарь / карта), но я всегда получаю Error allocating memory for array1
. Файл выглядит следующим образом (узлы слева, ребра справа):
40 15
30 12
30 13
76 80
76 80
76 80
Код:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int array1doublesize(int** array1,int nodes){
int* new_array=malloc(nodes*2*sizeof(int));
if(new_array==NULL){
printf("Error allocating memory on array1\n");
abort();
}
for(int i=0;i<nodes;i++){
new_array[i]=(*array1)[i];
}
nodes*=2;
free(*array1);
*array1=new_array;
return nodes;
}
typedef struct {
int start;
int end;
} path;
int cmp(const void *a,const void *b){
int l=((path*)a)->start;
int r=((path*)b)->start;
if(l>r)
return 1;
if(l<r)
return -1;
if(l==r)
return 0;
}
int doublesize(path** array,int n){
path* new_array=malloc(n*2*sizeof(path));
if(new_array==NULL){
printf("Error allocating memory\n");
abort();
}
for(int i=0;i<n;i++){
new_array[i]=(*array)[i];
}
free(*array);
*array=new_array;
n*=2;
return n;
}
int main()
{
int maxsize=10;
path* array=malloc(maxsize*sizeof(path));
if(array==NULL) {
printf("Error allocating memory\n");
abort();
}
FILE* fd=fopen("Test.txt","r");
if(fd==NULL) {
printf("Error opening file\n");
abort();
}
char buff[200];
int counter=0;
char c;
while(fgets(buff,200,fd)) {
c=buff[0];
if(c=='#') {
continue;
}
sscanf(buff,"%d%d",&array[counter].start,&array[counter].end);
counter++;
if(counter==maxsize){
maxsize=doublesize(&array,maxsize);
}
}
int i;
maxsize=counter;
qsort(&array[0],maxsize,sizeof(path),cmp);
counter = 0;
int nodes = 10;
int *array1 = malloc(nodes*sizeof(int));
if (array1 == NULL) {
printf("Error allocating memory\n");
}
for(i=0;i<maxsize;i++){
if(array1[counter]==array[i].start)
continue;
if(counter==nodes)
nodes=array1doublesize(&array1,nodes);
counter++;
array1[counter]=array[i].start;
}
counter=0;
for(i=0;i<nodes;i++){
printf("%d\n",array1[i]);
counter++;
}
free(array1);
fclose(fd);
free(array);
return 0;
}
Я пытался использовать GDB и получаю только Heap block at 007A0E60 modified at 007A0E90 past requested size of 28
Спасибо, что уделили время.