I have encountered a bug in the following linked list function and I have no idea what to do. The crazy part (to me) is that my code has been working perfectly up to now, and still does for several calls before hitting the bug.
The goal of this function is to add a new item (PathItem, which contains a BinaryItem) to the end of a linked list of PathItems. My function is as follows
void addPathItemAtEnd(struct PathItem * pathItem, struct BinaryItem * binaryItem) {
if (pathItem == NULL) {
pathItem = malloc(sizeof(struct PathItem));
pathItem->binaryItem = binaryItem;
pathItem->next = NULL;
} else {
while (pathItem->next != NULL) {
pathItem = pathItem->next;
}
struct PathItem * newPathItem = malloc(sizeof(struct PathItem));
newPathItem->binaryItem = binaryItem;
newPathItem->next = NULL;
pathItem->next = newPathItem;
}
}
with the problematic line being pathItem->next = newPathItem. I get the error EXC_BAD_ACCESS in the debugger. Once again, this code has functioned fine before, so I can’t understand what is happening now to upset it…
This seems to be an issue with reassigning the pointer variable. Don’t know what’s wrong.
Any thoughts, suggestions, criticisms. If needed, I can attach more/the rest of my code. Really need your help and thanks in advance.
Your main problem is that
pathItemis passed in as a copy so that changes to it are not reflected back in the original code. C uses a pass-by-value paradigm (C++ also uses pass by value but it at least has reference types so you don’t have to muck about with C’s obtuse pointer methods).I can’t see how this ever would have worked simply because, if the pointer you pass in as
pathItemis initially NULL, it stays NULL when you return. In other words, the list is always empty.Probably the easiest fix to that is to change the prototype to:
and then, wherever you currently have
pathIteminside that function, replace it with(*pPathItem).And, of course, call it with the pointer, changing (something like):
to:
As an aside, robust code would also check the return value from
mallocand act accordingly. While classwork and little personal projects may be able to get away with assuming no failures, that won’t cut it in the real world 🙂