Why do my pointers cause a segfault?

Viewed 50
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
  struct student
  {
    char name[50];
    char lname[50];
    int id;
    float GPA;
  };
void toAdd(vector<student*> *plist);
void toDelete(vector<student*>* plist);
void toPrint(vector<student*>* plist);
int main(){
  vector<student*> list;
  vector<student*>* plist = &list;
  char input[80];
  bool running = true;
  while (running == true){
    cout << "What would you like to do?" << endl;
    cin.getline (input,80);
    if(strcmp (input, "ADD") == 0){
      toAdd(plist);
    }
    else if(strcmp (input, "DELETE") == 0){
    }
    else if(strcmp (input, "PRINT") == 0){
    }
    else{
      cout << "That is not a valid response!" << endl;
        }
  }
}

void toAdd(vector<student*> *plist){
  student* stu;
  cout << "What a test!" << endl;
  cout << "First Name: ";
  cin.getline(stu->name,20);
  cout << "Last Name: ";
  cin.getline(stu->lname,20);
  cout << "ID: ";
  cin.getline(stu->id);
  cout << "GPA: ";
  cin.getline(stu->GPA);
  plist->push_back(stu);
}
void toDelete(){

}
void toPrint(){
}

I don't understand what I'm doing wrong. I've been going over this code for hours, and really need some help. I get the error "Segmentation Fault(core dumped)" When I run the code and try to input a name. I feel like this is probably really simple, but none of the online explanations are helping me. :(

2 Answers

You dereference a pointer which was not initialized. Before you call

cin.getline(stu->name,20);

You need to allocate its memory first using new

student* stu = new student;

Seg fault is usually caused when you are trying to access an area of memory location(to read or write) that is not allowed. In below line, within toAdd() method:

cin.getline(stu->name,20);

stu->name which is the equivalent for: (*stu).name is trying to dereference a pointer which was not initialized.

Furthermore, it is recommended to use smart pointers(Wrapper for raw(regular) pointers), since it allows you to manage the memory allocated for that pointer more efficiently. You can either choose unique or shared smart pointer.

Related