首页 > 解决方案 > 分段错误:11。急需解决代码(链表)

问题描述

我目前是 C++ 的初学者,从 C 转换而来。但我仍然是编程代码的初学者。

我目前正在寻找可以帮助我找到源代码问题的人(实际上是来自朋友)。源代码似乎在我朋友的编译器(Windows)上运行良好,但我目前在 MacOS Big Sur 上使用 VSCode。

#include <stdio.h>
#include <iostream>

using namespace std;

struct Data_mhs{
    char nim[12];
    char nilai;
};
struct mhs{
    Data_mhs data;
    mhs* next;
};

mhs* head;
mhs* tail;
mhs* baru;
mhs* del;

void inisialisasi(){
    head=NULL;
    tail=NULL;
}

void input(Data_mhs br)
{
    baru->data = br; //penugasan struktur
    baru->next = NULL;
    if(head==NULL)
    {
        head = baru;
        tail = head;
    }
    else
    {
        tail->next = baru;
        tail=baru;
    }
}

void hapus(){
    mhs simpan;
    if(head==NULL)
    {
        cout<<"\n(DATA TIDAK ADA YANG DIHAPUS)"<<endl;
    }
    else
    {
        simpan.data  = head->data;
        cout<<"\nData yang dihapus adalah ";
        cout<<simpan.data.nim<<"||"<<simpan.data.nilai<<endl;

        //hapus depan
        del = head;
        head = head->next;
        delete del;
    }
}

void menu(){
    char pilih, ulang;
    mhs tmp; 
start:
    cout<<"\nMenu : "<<endl;
    cout<<"1. Input data"<<endl;
    cout<<"2. Hapus data"<<endl;
    cout<<"Masukkan pilihan Anda : ";
    cin>>pilih;
    switch(pilih)
    {
        case '1' :
            fflush(stdin);
            cout<<"\nMasukkan NIM  : ";
            cin>>tmp.data.nim;
            cout<<"Masukkan nilai : ";
            cin>>tmp.data.nilai;

            input(tmp.data);
            break;
        case '2' :
            hapus();
            break;
        default :
            cout<<"Pilihan salah"<<endl;
    }
    cout<<"\nKembali ke menu (y/n) ?";
    cin>>ulang;
    if(ulang=='y'){
        goto start;
    }
}

int main(){
    inisialisasi();
    menu();

    return 0;
}

代码似乎运行良好,但在我的编译器(MacOS)上运行时代码似乎有问题,代码显示“Segmentation Fault:11”

图片

好像有问题:

baru->data = brr; //penugasan struktur
baru->next = NULL;

如果有人可以帮助解决我的问题,那将是一个很大的帮助!

标签: c++

解决方案


你从来没有分配baru指向任何东西。当你这样做时,baru->data = brr;你正在取消引用一个空指针。它是空的,因为全局指针被初始化为空。


推荐阅读