c++ - C++中链表的错误 “Abort signal from abort(3) (sigabrt) ”

标签 c++ c++11 pointers linked-list

以下代码用于基本的循环链表,但是当一个人输入一个较大的n(例如8位数字)值时,它将引发“abort(3)(sigabrt)中止信号”错误。我不确定这意味着什么,并且希望就我的代码解决此问题提供一些指导。
谢谢!

#include<bits/stdc++.h> 
using namespace std; 

//First I created a structure for a node in a circular linked list
struct Node 
{ 
    int data; 
    struct Node *next; 
}; 

// function to create a new node
Node *newNode(int data) 
{ 
Node *temporary = new Node; 
temporary->next = temporary; 
temporary->data = data; 
return temporary; 
} 

// This function finds the last man standing in
//the game of elimination
void gameOfElimination(int m, int n) 
{ 
    //first I created a circular linked list of the size which the user inputted 
    Node *head = newNode(1); 
    Node *prev = head; 
    //this loop links the previous node to the next node, and so on.
    for (int index = 2; index <= n; index++) 
    { 
        prev->next = newNode(index); 
        prev = prev->next; 
    } 
    prev->next = head; //This connects the last and first nodes in our linked list together. 

    //when only one node is left, which is our answer:
    Node *ptr1 = head, *ptr2 = head; 
    while (ptr1->next != ptr1) 
    { 

        int count = 1; 
        while (count != m) 
        { 
            ptr2 = ptr1; 
            ptr1 = ptr1->next; 
            count++; 
        } 

        /* Remove the m-th node */
        ptr2->next = ptr1->next; 
        ptr1 = ptr2->next; 
    } 

    printf ("%d\n ", 
            ptr1->data);
} 

//main program which takes in values and calls the function:
int main() 
{ 
    int n, p;
    cin>>n>>p;
    int m=p+1;
    gameOfElimination(m, n); 
    return 0; 
} 

最佳答案

SIGABRT通常在存在内存问题(堆损坏非常普遍)时发出。在您的代码中,我只看到new()运算符被调用,但是您没有从链接列表中删除任何未使用的节点!似乎您正在耗尽分配给进程的内存。

关于c++ - C++中链表的错误 “Abort signal from abort(3) (sigabrt) ”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59234645/

相关文章:

C++ 通用回调实现

c++ - 为什么它需要一个右值复制构造函数,即使它不会被调用?

c++ - 函数没有改变指针的值

C++:有什么方法可以从另一个函数访问字符串?

c++ - std::priority_queue 中的比较器

c++ - 为什么有两个 std::allocator::construct 函数?

c - 用静态关键字 : what is static, 声明的数组是指针还是整个数组?

c - 在运行时永久转换 void 指针

结构内部的c++ vector

c++ - 将 ASCII 字符串转换为 long long