Your code is accessing the array out of its bounds every time note[i]
is used.
In the (wrong) while loop it's always one past the last element (for example in the first iteration i
becomes 2, enough space for two double
s is allocated, but you access note[2]
which is the third).
While printing, you use n
as increasing loop index, but always print note[i]
instead of note[n]
.
It would be also a good practice to check the return values of all the library function used, such as open
, new
, realloc
and scanf
.
A quick fix of those issues could be the following snippet. Please, note that I used the same reallocation strategy as yours (every time), but as @Serge Ballesta pointed out, this can be inefficient. Look at the alternative showed in @Jean-François Fabre answer, for example.
#include <stdio.h>
#include <stdlib.h>
int main() {
double value,
*note = NULL,
*newptr = NULL;
int i,
size = 0;
char file_name[] = "numbers.txt";
FILE *ifile = fopen(file_name, "r");
if ( !ifile ) {
fprintf(stderr, "Error while opening file %s.\n", file_name);
exit(EXIT_FAILURE);
}
while ( fscanf(ifile, "%lf", &value) == 1 ) {
size++;
newptr = realloc(note, size * sizeof(double));
if ( !newptr ) {
fprintf(stderr, "Error while reallocating memory.\n");
free(note);
exit(EXIT_FAILURE);
}
note = newptr;
note[size - 1] = value;
}
for (i=0; i < size; i++) {
printf( "%lf\n", note[i]);
}
free(note); // <-- don't leak memory!
fclose(ifile);
return EXIT_SUCCESS;
}