My C program should read an input file and save it line for line in a linked list, then printing it. But when it's inserting the next line in the list, all elements in the list become the new element.
Input:
abc
def
ghi
Output:
ghi
ghi
ghi
I'm not sure but my guess is that it's not correctly allocating new memory for new elements in the list.
This is the code:
#include "listd.h"
#include <stdio.h>
void show(Value v) {
printf(v);
printf("\n");
}
int main( void ) {
List lines = init();
char a;
while(a != EOF){
a=getchar();
char currentline[256] = " ";
int i = 0;
while(a != '\n' && a != EOF){
currentline[i]=a;
a = getchar();
i++;
}
lines = insert(currentline, lines); //Here is probably the error
}
iterate(lines, show);
}
listd.h:
#include <stdlib.h>
#include <stdio.h>
#define DEFAULT 0
typedef enum {False ,True} Bool;
typedef char* Value;
typedef void (*VProc)(Value);
typedef struct _list {
Value val;
struct _list *next;
} Elem , *List;
List init() { return NULL; }
List insert(Value v, List l) {
List e = malloc( sizeof (Elem));
e->val = v;
e->next = l;
return e ;
}
void iterate(List l, VProc p) {
for (;!empty(l);l=tail(l)) p(head(l));
}
listd.h was given to us. But it was made for int, so I changed
typedef int Value;
to
typedef char* Value;
strdup()
orstrncpy()
into a new buffer. – tadmancamelCase
orMixedCase
variable names in favor of all lower-case while reserving upper-case names for use with macros and constants. It's style, so it up to you, but when you fail to follow it, it says a lot about your code before you even get to the details:)
– David C. Rankin