Backstory:
We were given a functional Linked List code and interface, and were told to change it to incorporate an array instead of next/prev pointers.
I decided to implement it as an in-order array that shifts whenever things are added.
The Problem:
I am getting segmentation faults whenever I try to add something to the array. The program doesn't seem to like me adding to the element_count variable in the List struct. If I comment the element_count++; it works, but then the underlaying code doesn't print anything out because it still thinks there are 0 elements.
Code:
The List struct
The List creationCode:typedef struct List_t { int element_count; /* number of elements in list */ int position; /* current (numeric) position in list */ Element *elementArray[MAX_SIZE]; } List;
The Element creationCode:List *listCreate(void) { List *new = NULL; /* new list */ if (!(new = calloc(1,sizeof(List)))) return(NULL); new->element_count = 0; new->position = 0; return(new); }
The list is then passed back into the abstracted code and passed back into each function.Code:Element *elementCreate(void *data) { Element *new; /* new element */ if (!(new = calloc(1,sizeof(Element)))) return(NULL); new->data = data; return(new); } /* elementCreate */
I didn't change anything in the interface or abstracted code, so it shouldn't be a problem there.
The Problematic Function
There is a function called listAddBefore which fails too, but it is essentially the same thing. The position just ends up in a different place.Code:List *listAddAfter(List *this, void *data) { int i; /* loop index */ Element *new; /* new element */ if (this->element_count >= MAX_SIZE) /*Array boundary check*/ return (NULL); if (!(new = elementCreate(data))) /*new element*/ return (NULL); if (this->element_count == 0) { this->elementArray[0] = new; this->position = 1; } else if (this->element_count > 0) /* Traverse array */ { for (i = this->element_count ; i > this->position ; i--) { this->elementArray[i] = this->elementArray[i-1]; } this->elementArray[this->position+1] = new; } this->element_count++; /* This is where it breaks */ return(this); } /* listAddAfter */
Any help would be appreciated. I can give more code if requested.



LinkBack URL
About LinkBacks




I'm running on Ubuntu and compiling with gcc.
Enjoy.