I have experience in higher level languages, but I’m new to C. I’ve been given an implementation of a singly linked list. Every time I try to iterate through the list I walk out of memory (at least I assume that’s what is happening). Here is the implementation of the list:
/*Vertex data type.*/
typedef struct vnode {
struct vnode *NEXT;
int DATA;
} VertexBody;
typedef VertexBody *TypeVertex;
/*List data type (no header, just a pointer to first item).*/
typedef TypeVertex TypeList;
Here is my print function:
void print_list(TypeList *L) {
TypeVertex v=*L;
while(NEXT(v)!=NULL) {
printf("%d\n", DATA(v));
v=NEXT(v);
}
printf("%d\n", DATA(v));
}
Running print_list gives the following output (say the list contains 3 vertices, with data set to 1,2,3 respectively):
1
2
3
-94064
Then the program crashes. What’s the problem?
EDIT: changed “traverse” to “iterate through” in first paragraph.
It seems that I misidentified the issue. The program was crashing because I had forgotten to allocate memory for the list. I feel like an idiot, but at least I can move on. Thank you for your answers.