D
difeiz
Greetings all,
I am working on a program and encountered a problem recently. The program is simplified (but the problem is still reproduceable):
test file can be generated by:
~$ seq 1 100 > test
In main function I malloced a double pointer (rates_1) with a size of a double type, then I passed a pointer (&rates_1) to this double pointer (rates_1) to the function read_in_rates.
The read_in_rates function counted the lines in test file and trying to reallocate the pointer, access to the pointer (*rates) will guarantee a segfault when i >=1 on my machine.
I'm running this program on linux on virtualbox, memory spaces are plenty, I have several other malloc and realloc for some structure types and they are working fine, could anyone point out where the problem is? Thanks in advance.
Cheers,
Difei
I am working on a program and encountered a problem recently. The program is simplified (but the problem is still reproduceable):
Code:
#define _GNU_SOURCE
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void
read_in_rates(const char *filename, double **rates)
{
int i, lines = 0;
char ch;
FILE *rates_file = fopen(filename, "r");
do {
ch = fgetc(rates_file);
if (ch == '\n') lines++;
} while (ch != EOF );
*rates = realloc(*rates, lines * sizeof(**rates));
rewind(rates_file);
for(i = 0; i < lines; i++) {
fscanf(rates_file, "%lf", &(*rates)[i]);
printf("%lf\n", *rates[i]);
}
}
int
main(void)
{
int i;
double *rates_1 = malloc(sizeof(*rates_1));
read_in_rates("./test", &rates_1);
for(i = 0; i <= 80; i++)
printf("%i\t%lf\n", i, rates_1[i]);
exit(EXIT_SUCCESS);
}
test file can be generated by:
~$ seq 1 100 > test
In main function I malloced a double pointer (rates_1) with a size of a double type, then I passed a pointer (&rates_1) to this double pointer (rates_1) to the function read_in_rates.
The read_in_rates function counted the lines in test file and trying to reallocate the pointer, access to the pointer (*rates) will guarantee a segfault when i >=1 on my machine.
I'm running this program on linux on virtualbox, memory spaces are plenty, I have several other malloc and realloc for some structure types and they are working fine, could anyone point out where the problem is? Thanks in advance.
Cheers,
Difei