我正在尝试使用链表进行出列,我可以从队列的正面或背面添加随机元素,并希望随机获取和删除它们。我的程序运行,但idk为什么,在某个地方它失败了。随机它有分段错误,我找不到问题。这是我的代码:
我的功能:
void dequeue_put_back(struct DeQueue *q, void *elem)
{
struct Node *n = new_node(elem, q->elem_size);
if (q->head == NULL) {
q->head = n;
q->head->prev = NULL;
q->tail = n;
q->tail->prev = head;
} else {
q->tail->next = n;
q->tail->prev = q->tail;
q->tail = n;
}
q->n_elems++;
}
void dequeue_get_front(struct DeQueue *q, void *elem)
{
memcpy(elem, q->head->elem, q->elem_size);
struct Node *to_del = q->head;
q->head = q->head->next;
free_node(to_del);
q->head->prev = NULL;
q->n_elems--;
}
void dequeue_put_front(struct DeQueue *q, void *elem)
{
struct Node *n = new_node(elem, q->elem_size);
if (q->head == NULL) {
q->head = n;
q->tail = n;
} else {
n->next = q->head;
q->head->prev = n;
q->head = n;
}
q->n_elems++;
}
void dequeue_get_back(struct DeQueue *q, void *elem)
{
memcpy(elem, q->tail->elem, q->elem_size);
struct Node *to_del = q->tail;
q->tail = q->tail->prev;
free_node(to_del);
q->n_elems--;
}
MY MAIN:
int main(int argc, char **argv)
{
srand(time(0));
struct DeQueue *q = dequeue_new(sizeof(int));
int t = 0;
while (t++ < SIM_DURATION) {
int action = rand() % 5;
int r;
switch (action) {
case 0: // add random number to dequeue from back
r = rand() % 10;
dequeue_put_back(q, &r);
printf("t = %d: Adding %d to dequeue from its back, dequeue size = %d\n",
t, r, dequeue_size(q));
break;
case 1: // get the next item from front
if (!dequeue_is_empty(q)) {
dequeue_get_front(q, &r);
printf("t = %d: Took %d from dequeue from its front, dequeue size = %d\n",
t, r, dequeue_size(q));
} else {
printf("t = %d:\n", t);
}
break;
case 2: // add random number to dequeue front
r = rand() % 10;
dequeue_put_front(q, &r);
printf("t = %d: Adding %d to dequeue from its front, dequeue size = %d\n",
t, r, dequeue_size(q));
break;
case 3: // get the next item from back
if (!dequeue_is_empty(q)) {
dequeue_get_back(q, &r);
printf("t = %d: Took %d from dequeue from its back, dequeue size = %d\n",
t, r, dequeue_size(q));
} else {
printf("t = %d:\n", t);
}
break;
default:
case 4: // do nothing
printf("t = %d:\n", t);
break;
}
fflush(stdout);
sleep(1);
}
dequeue_free(q);
return EXIT_SUCCESS;
}
AND OUTPUT(必须运行到t = 30):
t = 1:
t = 2:
t = 3: Adding 6 to dequeue from its front, dequeue size = 1
t = 4:
t = 5: Adding 7 to dequeue from its back, dequeue size = 2
t = 6: Adding 4 to dequeue from its back, dequeue size = 3
t = 7:
t = 8: Adding 8 to dequeue from its back, dequeue size = 4
t = 9: Adding 9 to dequeue from its front, dequeue size = 5
t = 10: Adding 1 to dequeue from its back, dequeue size = 6
t = 11: Took 1 from dequeue from its back, dequeue size = 5
Segmentation fault
答案 0 :(得分:0)
在调试器中运行它。当它崩溃时,它应该打印出堆栈跟踪,告诉你崩溃的代码行。