edward@ingr.com (Edward Reynolds) (04/19/89)
Hi Guys, We are having a problem with creating/freeing linked lists. This program was written with TurboC very late at night and is causing great headaches. If you got an extra free minute would you please take a look??!! ;-) Thanks!!!! This program just builds a linked list of structures containing the names of the files in a a directory. It then frees each node in the list and repeats the process again and again. (There is a purpose to this but no need to go into why I'm doing this.) The list builds and frees correctly the first time through the loop but not any time thereafter. The first time through, as it is building the list and displaying the filenames and pointer fields, the right pointer of the last node is NULL as it is linked and just before the list is freed. The second time through, the right pointer of the las node is NULL as it is linked BUT just before the list is freed, I notice it is NOT NULL. Any ideas as to why???? The memory is freed only the first time through the free function and not on any subsequent call. WHY???? It would be greatly appreciated if anyone has any comments, suggestions, or ideas as to what might be wrong! Is there a problem with the MALLOC calls? This is run on a PC with TurboC. THANKS IN ADVANCE!!!! John S. /** This is the structure being linked **/ struct A_File { char File_Name[14]; struct A_File *left; struct A_File *right; }; struct A_File *Top=NULL; /* points to first node in list */ struct A_File *Last=NULL; /* points to last node in list */ struct A_File *Head_ptr=NULL; /* Head pointer of linked list */ main() { for (run this 5 times or so) { if (Head_ptr != NULL) { Que_Close(); /* Close linked list; function is at the end */ } /* BUILD LIST OF FILES */ do { if Appending the first structure { if((p=(struct A_File *)malloc(sizeof(struct A_File)))==NULL) { printf("allocation error - aborting"); exit(0); } } else { if((p->right=(struct A_File *)malloc(sizeof(struct A_File)))==NULL) { printf("allocation error - aborting"); exit(0); } p = p->right; } if it is a file we want to append to list { strcpy(p->File_Name, Name); Que_Append(p); } }while more files to append } } /* END PROGRAM */ /* FUNCTION TO CLOSE LINKED LIST */ Que_Close() { struct A_File *d; struct A_File *dnext; for (d = Head_ptr; d != NULL; d = dnext) { dnext = d->right; free (d); } {| Set all pointers to NULL |} /* FUNCTION TO APPEND A LINK TO LIST */ Que_Append (p) /* p is structure to append */ struct A_File *p; { p->right = NULL; if this is the first structure in linked list { Head_ptr = p; Top = p; Last = p; p->left = NULL; } else { Last->right = p; p->left = Last; Last = p; } } /* END FUNCTION QUE_APPD */ mailpath ingr!b11!strato!edward "QUOTES?? I don't need no stinking quotes!!"