This program will generate a list of temporary filenames using linked lists.I dont get an error when I compile, but when I execute it just hangs. This is my code:
Code:
#include <stdio.h>
#include <stdlib.h>
#ifdef NODEISSTRING
#define NODEDATATYPE(var) char var [20]
#else
#define NODEDATATYPE(var) int var
#endif
struct node {
NODEDATATYPE(data);
struct node *next;
};
void insertlist(struct node **list, NODEDATATYPE(val)){
struct node *new, *cur, *back;
int found;
new = malloc(sizeof(struct node));
if ( new == NULL){
fprintf(stderr, "Cannot allocate new.\n");
exit(1);
}
/* pick correct comparison based on data type */
#ifdef NODEISSTRING
strcpy(new -> data, val);
#else
new -> data = val;
#endif
back = NULL;
cur = *list;
found = 0;
while ( cur != NULL && !found )
/* pick the right comparison based on whether we are a string */
#ifdef NODEISSTRING
if ( strcmp(val, cur -> data) <= 0 )
#else
if ( val <= cur -> data )
#endif
found = 1;
else {
back = cur;
cur = cur -> next;
}
new -> next = cur;
if ( back == NULL ) /* must be first element */
*list = new;
else
back->next = new;
}
void deletelist(struct node **list) {
struct node *n;
n = (*list) -> next;
if ( n == NULL )
(*list) -> next = NULL;
else
/* copy whole struct */
**list = *n;
free(n);
}
struct node *searchlist(struct node *list, NODEDATATYPE(val)) {
struct node *cur;
int found;
cur = list;
found = 0;
while ( cur != NULL && !found ) {
#ifdef NODEISSTRING
if ( strcmp(cur -> data, val ) == 0 )
#else
if ( cur -> data == val )
#endif
found = 1;
else
cur = cur -> next;
}
return cur;
}
int emptylist(struct node *list){
return (list == NULL);
}
void dumplist(struct node *list) {
struct node *p;
p = list;
while ( p != NULL ) {
#ifdef NODEISSTRING
printf("%s\n", p -> data);
#else
printf("%d\n", p -> data);
#endif
p = p -> next;
}
}
void clearlist(struct node **list) {
struct node *p, *c;
p = *list;
while ( p != NULL ) {
c = p;
p = p -> next;
free(c);
}
*list = NULL;
}
int main () {
struct node *list, *p;
FILE *out;
int x;
out = fopen("d6.out", "w"); /* Opening file d6.out for writing */
if(out == NULL) { /* File test for out */
perror("fopen: d6.out");
exit(1);
}
for(x = 0; x < 15000; x++)
insertlist(&list, tmpnam(NULL));
p = list;
while ( p != NULL ) {
fprintf(out, "%s\n", p -> data);
fprintf(out, "%d\n", p -> data);
p = p -> next;
}
clearlist(&list);
fclose(out);
return 0;
}