So first off, this is a homework assignment, so please don't write any code for me, just point out where my code is wrong.
The basics of the code is that it's a 'address/balance' book. I've got a struct with my variables, but for some reason, my doubly linked list is getting all messed up and I can't figure out how. With a bit of fancy (not really) debugging, I've figured out that I think the fgets(string, 200, file); line is overwriting my head->name pointer somehow, which seems to throw the rest of the code off. Relevant code snippets here:
Populating the List:
void populate_list(char* filename){
FILE *file = NULL;
char* name = NULL;
char* streetaddress = NULL;
char* city = NULL;
char* state = NULL;
char line[200];
int zip;
float balance;
file = fopen(filename,"r");
if(file==NULL){
printf("Invalid input file\n");
exit(1);
}
if(file == 0){
printf("Invalid file.\n");
exit(1);
}
while(!feof(file)){
fgets(line, 200, file);
name = strtok(line, ",");
streetaddress = strtok(NULL, ",");
city = strtok(NULL,",");
state = strtok(NULL,",");
zip = atoi(strtok(NULL,","));
balance = atof(strtok(NULL,","));
strip_spaces(name);
strip_spaces(streetaddress);
strip_spaces(city);
strip_spaces(state);
add_node(name, streetaddress, city, state, zip, balance);
}
fclose(file);
return;
}
Then the add_node code:
void add_node(char* name, char* streetaddress, char* city, char* state, int zip, float, balance){
struct customer* addnode = NULL;
if(find_duplicate(name)){
print_filler(1);
printf("DUPLICATE RECORD: %s\n", name);
return;
} else {
addnode = (struct customer *) malloc(sizeof(struct customer));
addnode->name = name;
addnode->streetaddress = streetaddress;
addnode->city = city;
addnode->state = state;
addnode->zip = zip;
addnode->balance = balance;
if(head == NULL) {
head = addnode;
addnode->prev = NULL;
} else {
tail->next = addnode;
addnode->prev = tail;
}
tail = addnode;
addnode->next = NULL;
}
print_list();
return;
}
The bug seems to be happening after the first time add_node is called and happens when fgets() goes off a second time. It's overwriting head->name with the entire fgets() line for some reason.
There other random irritating bugs I haven't pinned down yet, but this one I think may be the source of the others.
Full code is here, if it helps: http://pastebin.com/k0pqyvT0
My guess is it's something to do with the head->name pointer being overwritten by fgets(), but I can't for the life of me figure out what exactly is doing this, any help/advice would be appreciated.
Edit: Solution was to implement strdup() and duplicate the strings when they're passed to add_node(). Thanks for all the answers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With