0

I will read some double information in file but my code make error. This error message is "realloc(): invalid next size". How do I fix this error?

If I reduce the number of readings in the file, the error disappears. Why didn't I understand?

#include <stdio.h>
#include <stdlib.h>
#define p1 0.5
#define p2 20

int main(void){

FILE *fp;
int i,j;

double *real_number;
double *temp;

real_number = (double *) malloc(sizeof(double) * 1);

fp = fopen("input.txt","r");

for(i = 0 ; !feof(fp) ; ++i)
{
    real_number = (double *) realloc(real_number,sizeof(double)*2);

    fscanf(fp,"%lf",&(real_number[i]));
    printf("%.2f \n",real_number[i] );
    printf("i:%d\n",i );

}

return (0);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    I think you want to allocate memory for the current number of values +1 in the loop, but you actually allocate the memory for 2 double values. `real_number = (double *) realloc(real_number,sizeof(double)*(i+1));` – Bodo Jun 17 '19 at 12:47
  • 2
    [why `while (!feof())` is always wrong](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong) – dbush Jun 17 '19 at 12:51

2 Answers2

1

This statement

real_number = (double *) realloc(real_number,sizeof(double)*2);

always allocates a memory of the same size that is only for two doubles.

So this loop

for(i = 0 ; !feof(fp) ; ++i)

can invoke undefined behaviour when i is greater than 1.

Also the condition in the loop is incorrect because the end of the file can occur in this statement

fscanf(fp,"%lf",&(real_number[i]));

and it is not checked.

The loop can look for example the following way

double *real_number = NULL;
double value;

size_t i = 0;

for ( ; fscanf( fp, "%lf", &value ) == 1; i++ ) 
{
    double *tmp = realloc( real_number, ( i + 1 ) * sizeof( double ) );

    if ( tmp == NULL ) break;

    real_number = tmp;
    real_number[i] = value;
}

In this case after the loop the variable i will contain the number of inputted doubles.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You need to allocate memory for the current number of values +1 in the loop, but you actually allocate the memory for 2 double values.

Change the realloc call to

real_number = (double *) realloc(real_number,sizeof(double)*(i+1));

BTW: You should check the result of malloc and realloc and all other functions that may report an error.

The loop for(i = 0 ; !feof(fp) ; ++i) is wrong. feof does not tell you that you will reach EOF, but only that you have reached EOF after a failed read operation. You should check the result of fscanf and after this you can use feof and ferror to distinguish between EOF, error related to the file or other errors like unexpected input. See Why is “while (!feof(file))” always wrong?

Bodo
  • 9,287
  • 1
  • 13
  • 29