Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do my pointers cause a segfault?

#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. :(

like image 233
RamenCat Avatar asked Feb 15 '26 14:02

RamenCat


1 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;
like image 147
Zamrony P. Juhara Avatar answered Feb 17 '26 03:02

Zamrony P. Juhara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!