I have a **void where each position point to *void that point to my struct record with 3 fields (*char, int, float). I want to load data from a csv in my struct, but when it's time to reallocate memory, because size is equal to array's capacity, I got realloc(): invalid next size. I did not get my printf("realloc fails") so I think that tmp is not null, but anyway I lost my memory pointer.
<pre>struct record{
int id;
char* field1;
int field2;
float field3;
};
long array_size = 0;
long array_capacity = INITIAL_CAPACITY;
void** array;
void** array_create(){
void **array = (void**)malloc(INITIAL_CAPACITY*sizeof(void*));
if(array == NULL){
fprintf(stderr, "array_create: unable to allocate memory for the array");
exit(EXIT_FAILURE);
}
return array;
}
void add_on_array(void** array, void* elem){
if(array == NULL){
fprintf(stderr,"add_on_array: array parameter cannot be NULL");
exit(EXIT_FAILURE);
}
if(elem == NULL){
fprintf(stderr,"add_on_array: elem parameter cannot be NULL");
exit(EXIT_FAILURE);
}
if(array_size >= array_capacity){
void** tmp = realloc(array, 2*(sizeof(void*)*array_capacity));
if(tmp == NULL){
printf("Realloc fails\n");
exit(EXIT_FAILURE);
}
array = tmp;
array_capacity = 2*array_capacity;
}
array[array_size] = elem;
array_size++;
}
<pre>static void load_array(const char* file_name){
char *read_line_p;
char buffer[4096];
int buf_size = 4096;
array = (void**)malloc(array_capacity*sizeof(void*));
FILE *fp;
printf("\nLoading data from file...\n");
fp = fopen(file_name,"r");
if(fp == NULL){
fprintf(stderr,"load_array8: unable to open the file");
exit(EXIT_FAILURE);
}
while(fgets(buffer,buf_size,fp) != NULL){
read_line_p = strdup(buffer);
if(read_line_p == NULL){
fprintf(stderr,"main: unable to allocate memory for the read line");
exit(EXIT_FAILURE);
}
char *id_field_in_read_line_p = strtok(read_line_p, ",");
char *field1_in_read_line_p = strtok(NULL,",");
char *field2_in_read_line_p = strtok(NULL,",");
char *field3_in_read_line_p = strtok(NULL, ",");
char *field1 = malloc((strlen(field1_in_read_line_p)+1)*sizeof(char));
if(field1 == NULL){
fprintf(stderr,"main: unable to allocate memory for the string field of the read record");
exit(EXIT_FAILURE);
}
int id = atoi(id_field_in_read_line_p);
strcpy(field1,field1_in_read_line_p);
int field2 = atoi(field2_in_read_line_p);
float field3 = atof(field3_in_read_line_p);
struct record *record_p = malloc(sizeof(struct record));
if(field1 == NULL){
fprintf(stderr,"main: unable to allocate memory for the read record");
exit(EXIT_FAILURE);
}
record_p->id = id;
record_p->field1 = field1;
record_p->field2 = field2;
record_p->field3 = field3;
add_on_array(array, (void*)record_p);
free(read_line_p);
}
fclose(fp);
printf("\nData loaded\n");
stampa_array(array, array_size);
}
What I have tried:
I already search on internet, but nothing. I thing it could be a memory leak, but I don't understand why.