I'm trying to write a small doubly linked lists program in C, but for some reason it gives me undefined behavior for the first element. I want it to have an empty cell at the beginning which links the first and last elements. So it's like this: ... <-> Second Last <-> Last <-> Empty Cell <-> First <-> Second <->...
The first element is a random value but the next ones work. For example, if my input file is 1 2 3 4 5, the output will be <undefined>
2 3 4 5, where undefined can be any number C wishes to give me.
The weird part is that it works flawlessly in debug mode too (using MinGW Developer Studio as I got used to it from school). It also works good under Linux (using gcc for compilation).
This is the code:
#include <stdio.h>
#include <stdlib.h>
typedef struct Nod {
struct Nod *next, *ant;
int x;
} Nod_t, *List_t, **AList_t;
void PrintList (List_t sant){
List_t lista = sant->next;
while(lista != sant){
printf("%i ", lista->x);
lista = lista->next;
}
}
List_t PopulateList(char* fis){
List_t lista, sant;
int nr;
FILE *f = fopen(fis, "rt");
sant = (List_t)malloc(sizeof(List_t));
sant->next = sant->ant = NULL;
lista = sant;
//First node
while(!feof(f)){
fscanf(f, "%i", &nr);
lista->next = (List_t)malloc(sizeof(List_t));
lista->next->x = nr;
lista->next->ant = lista;
lista = lista->next;
}
sant->ant = lista;
lista->next = sant;
return sant;
}
int main (){
List_t lista1;
lista1 = PopulateList("1.txt");
PrintList(lista1);
return 0;
}
Way better indentation here: http://pastebin.com/NVQqaYHK