当前位置: 动力学知识库 > 问答 > 编程问答 >

Segmentation fault (core dumped) ? what is it and why is caused ??? ( doubly circular linked list program in c++)

问题描述:

This question already has an answer here:

  • What is a segmentation fault?

    10 answers

网友答案:

You typically get segmentation faults when using illegal pointers (null or uninitialized pointers, or pointers pointing to unallocated or otherwise illegal memory).

In your case it's easy to see what one of the problems are, it's in the dcllnode constructor where you do

prev = next;
next = prev;

When you do these assignments the pointers next and prev are uninitialized, and their values are indeterminate. Assigning them to each other like this will not initialize them, just make them both have the same indeterminate value. Later when you dereference these pointers you will have undefined behavior leading to your segmentation fault and the crash.

What you probably should to is to initialize both pointers to null:

prev = nullptr;  // or 0
next = nullptr;  // or 0

[Note: In C++ don't use NULL, use either nullptr (preferred) or if you don't have it then plain 0.]

网友答案:

To complete joachim's answer, in these two statements:

(head->next)->prev = x;
(head->prev)->next = x;

head->next and head->prev can be nullptr so you have to check it before dereferencing the pointer.

分享给朋友:
您可能感兴趣的文章:
随机阅读: