I have this function which reads some strings in this format:
2
London Berlin 220 1.5
London Milan 280 2.5
...
and same stuff should be read againg...
2 is the number of strings after itself. For this purpose I have the following function:
void allocate_info(FILE* fptr, info_t* cities_info, int N){
int tmp_flights;
int i = 0;
while(fscanf(fptr, "%d", &tmp_flights) == 1){
printf("%d\n", tmp_flights); // this print!!!
char tmp_departure[LENGTH], tmp_arrival[LENGTH];
int tmp_price;
float tmp_duration;
for(int i = 0; i < tmp_flights; i++){
fscanf(fptr, "%s %s %d %f", tmp_departure, tmp_arrival, &tmp_price, &tmp_duration);
strcpy(cities_info[i].departure, tmp_departure);
strcpy(cities_info[i].arrival, tmp_arrival);
cities_info[i].price = tmp_price;
cities_info[i].duration = tmp_duration;
}
}
}
"this print!!!" actually prints all numbers but at the end program fails (error 1). this is my main function:
int main(void) {
FILE* fptr = fopen("D:/ap2/lab02ex01/file.txt", "r");
int N;
info_t* cities_info = (info_t*)malloc(sizeof(info_t) * N);
N = read_number_of_cities(fptr); // some other function
allocate_info(fptr, cities_info, N); // ERROR HERE?!?
return 0;
}
I am very confused about it, because it prints everything correctly but program for some reason fails. Help me out please.
Using the variable N
in your main
function before initializing it is invoking undefined behaviour since the value of N
is indeterminate at the point where it's used.
If you compile with warnings on (-Wall -Wextra
), you would see a warning like the following, among possibly others.
warning: variable 'N' is uninitialized when used here [-Wuninitialized]
If you compiled with -Wall -Wextra -Werror
this would have been treated as a compilation error and would have to have been fixed before you could ever run the program in the first place.
You would also have seen warnings about ignoring the return value of fscanf
, and with -Werror
have been forced to fix that issue.