I'm getting a seg fault in this program on linked lists, and frankly, I'm not surprised because this topic has been giving me a hell of a lot of trouble.
What I have so far is
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _Node {
int value;
struct _Node *next;
} NodeT;
NodeT *makeNode(int data);
NodeT *joinList(NodeT *head1, NodeT *head2);
void printList(NodeT *head);
void freeList(NodeT *head);
int main(int argc, char *argv[]) {
NodeT *l = NULL;
NodeT *head = NULL;
NodeT *prevl = NULL;
int data = 0;
int numScanned = 1;
int count = -1;
while (numScanned) {
printf("Enter an integer: ");
numScanned = scanf("%d", &data);
if (numScanned) {
count++;
l = makeNode(data);
if (count == 0) {
head = l;
} else {
prevl = l;
}
l->next = joinList(prevl, l);
}
}
for (l = head; l!=NULL; l = l->next) {
printList(l);
}
return EXIT_SUCCESS;
}
NodeT *makeNode(int data) {
NodeT *new;
new = malloc(sizeof(NodeT));
if (new == NULL) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
new->value = data;
new->next = NULL;
return new;
}
NodeT *joinList(NodeT *head1, NodeT *head2) {
head1->next = head2;
return head1->next;
}
void printList(NodeT *head) {
NodeT *cur = head;
while (cur != NULL) {
printf("%d", cur->value);
cur=cur->next;
if (cur != NULL) {
printf("->");
}
}
printf("\n");
}
void freeList(NodeT *head) {
NodeT *cur;
cur = head;
while (cur != NULL) {
NodeT *tmp = cur->next;
free(cur);
cur = tmp;
}
}
I'm fairly comfortable with all functions except the joinList one, and I'm unsure about the way my main has been set out either. If someone can be bothered to scrutinize my program, I'd be very thankful.