单向列表中的分段违规信号

Segmentation violation signal in unidirectional list

我正在尝试制作一个单向列表,其中的节点包含一个值和一个指向下一个节点的指针(最后一个节点中的指针应该是一个 nullptr)。

然而,事情并没有按计划进行。它的编译没有任何问题,但是当我尝试 运行 它时,我得到了这个致命错误情况: SIGSEGV - 分段违规信号。

它认为它正在尝试访问它没有使用权限的内存,还是什么?另一个常见原因是意外的“=”而不是“==”,但这似乎不是这里的问题。

当我尝试在我的测试文件中构建一个没有任何节点的 Sorted_List 时,似乎发生了错误,如下所示:

Sorted_List empty_list{};

这是我认为可能与错误相关的代码:

Sorted_List.cc

#include "Sorted_list.h"
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

Sorted_List::Sorted_List() : head{nullptr} {}

Sorted_List::Sorted_List(initializer_list<int> i)
  :Sorted_List()
{
  for (auto ii : i)
    {
      add_val(ii);
    }
}

Sorted_List::~Sorted_List()
{
  if (!check_empty())
    {
      Node* del = head;
      while(del != nullptr)
    {
      Node* next = del->next;
      delete del;
      del = next;
    }
    }
}

bool Sorted_List::check_empty() const
{
  return (head->value == 0 && head->next == nullptr);
}


void Sorted_List::del_val(int num)
{
  Node* del = head;
  if (num == 1)
  {
    head = del->next;
    delete del;
  }
  for (int i = 1; i < num - 1; i++)
    {
      del = del->next;
    }
}

void Sorted_List::add_val(int num)
{
  Node* temp = new Node;
  temp->value = num;
  if (head == nullptr || head->value >= temp->value)
    {
      temp->next = head;
      head = temp;
    }    
  else
    {
      Node* current = head;
      while(current->next != nullptr && current->next->value <temp->value)
    {
      current = current->next;
    }
      temp->next = current->next;
      current->next = temp;
    }
}
string Sorted_List::print( Sorted_List& list)
{
  Sorted_List::Node* temp;
  stringstream list_stream;
  for(temp = list.head; temp != nullptr; temp = temp->next) 
    {
      list_stream << temp->value;
      if(temp->next != nullptr)
    list_stream << ", ";
    }
  return list_stream.str();
}

Sorted_List.h

#ifndef SORTED_LIST_H
#define SORTED_LIST_H

#include <string>
#include <iostream>
#include <initializer_list>
#include <string>

class Sorted_List
{
private:
    class Node
    {
    public:
        int value{};
        Node* next{};
    };
Node* head{};

public:
    Sorted_List();
    Sorted_List(std::initializer_list<int>);
    ~Sorted_List();

    std::string print(Sorted_List&);
    void add_val(int num);
    bool check_empty() const;
    void del_val(int num);
};

#endif

Sorted_List_test.cc

#define CATCH_CONFIG_MAIN
#include "Sorted_list.h"
#include "catch.hpp"
#include <iostream>
#include <string>
using namespace std;

TEST_CASE(" EMPTY ")
{  
  Sorted_List empty_list{}; // this is where the error occurs
  //REQUIRE(empty_list.check_empty() == true);
  //REQUIRE(empty_list.print(empty_list) == "");
}

有什么线索吗?

如果您使用调试器,您会发现当 empty_list 对象被 破坏 时会发生崩溃。更准确地说,在从析构函数调用的 check_empty 函数中。

这是因为默认构造函数将 head 设置为空指针,然后在 check_empty 中取消引用此空指针。

您的 check_empty 函数应检查 head 是否为空指针。