Segmentation fault:11. In need for solving code (Linked List)

  c++

i am currently a beginner at C++, transfering from C. But i am still a beginner at programming codes. I am currently looking for someone who can help me find the problem at my source code (actually, it’s from a friend). The source code seems to be running fine at my friend’s compiler (Windows), but I am currently using VSCode on MacOS Big Sur.

#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;
}

The code seems to be running fine, but there seems to be something wrong with the code while running on my compiler (MacOS), the code shows "Segmentation Fault:11"
https://i.stack.imgur.com/c8Ee0.png

There seems to be a problem at

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

It would be a great help if someone could help give a solution to my problem!
Thank you!

Source: Windows Questions C++

LEAVE A COMMENT