You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

图书馆模拟程序出现Segmentation Fault,无法访问公共变量

图书馆模拟程序Add函数段错误问题

我正在编写一个图书馆模拟程序,其中的add函数出现了Segmentation Fault,不清楚故障原因。

函数开头代码:

void add()
{
    Book* newBook = new Book;
    Book* temp = new Book;
    temp = head;
    string tempstring;
    int id;
    int n;

    cout << "Enter the ID of the book you wanna add: ";
    cin >> id;

下方的if条件用于检查链表是否为空,若为空则添加书籍并退出函数:

if(head == NULL)
    {
        newBook->id = id;
        cout << "Enter the name of the Book: ";
        cin >> tempstring;
        newBook->nameOfTheBook = tempstring;
        cout << "Enter the Name of the Author: ";
        cin >> tempstring;
        newBook->author = tempstring;
        cout << "Enter The number of copys you're going to add: ";
        cin >> n;
        newBook->numOfBooks += n;

        newBook->next = NULL;
        head = newBook;
        return;
    }

我的错误出现在if(temp->id == id)这个条件判断处:

if(

    while(temp != NULL)
    {
        if(temp->id == id)
        {
            temp->numOfBooks += 1;
            if(temp->avaliable == 0)
            temp->avaliable = 1;
            return;
        }
        temp = temp->next;
    }
    newBook->id = id;
    cout << "Enter the name of the Book: ";
    cin >> tempstring;
    newBook->nameOfTheBook = tempstring;
    cout << "Enter the Name of the Author: ";
    cin >> tempstring;
    newBook->author = tempstring;
    cout << "Enter The number of copys you're going to add: ";
    cin >> n;
    newBook->numOfBooks += n;

此时temp的值应为NULL,我尝试将temp替换为newBook:

newBook->prev = temp->prev;
    newBook->next = NULL;
    temp->prev->next = newBook;

    newBook->avaliable = 1;   
}

内容的提问来源于stack exchange,提问作者kan3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 05:00:29