I’m trying to destroy my deque but somehow I fail with pointers. I have written the following code (deque is a pointer to a pointer, which points to the first element of the deque). The DequeItem’s are structs with fields next (pointer to next element) and data (void *).
void deque_destroy(DequeItem **deque) {
DequeItem *temp;
DequeItem *item;
for (item = *deque; item != NULL; item = temp) {
printf("%d", *((int*)((item)->data)));
temp = item->next;
free(item);
}
}
The struct declaration is:
struct DequeItem {
void *data; // Data stored in the deque item
struct DequeItem *previous; // Pointer to the previous DequeItem in the ring
struct DequeItem *next; // Pointer to the next DequeItem in the ring
};
typedef struct DequeItem DequeItem;
The problem was, that the next-pointer of the last element (back element) in the deque will point to the first element (front element) even though the first element has been destroyed. I fixed this by setting
before the for-loop above. Thanks for help!