Segmentation fault using struct

Seg fault after "Enter full Name line. Indicated below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <string>

using namespace std;

  struct student
  {
    int studentID;
    double gpa;
    string fullName;
    int units;
  };


int main()
{
  student info[1];

  cout << "STUDENT 1" << endl;

  cout << endl << "Enter student ID" << endl;
  cin >> info[0].studentID;

  cout << endl << "Enter GPA" << endl;
  cin >> info[0].gpa;

  cout << endl << "Enter full name" << endl;
  cin.ignore();
  getline(cin, info[0].fullName);

  cout << endl << "Enter units taking" << endl;
  cin >> info[0].units;



  cout << endl << endl << "STUDENT 2" << endl;

  cout << endl << "Enter student ID" << endl;
  cin >> info[1].studentID;

  cout << endl << "Enter GPA" << endl;
  cin >> info[1].gpa;

  cout << endl << "Enter full name" << endl;//Segmentation fault after this line
  cin.ignore();
  getline(cin, info[1].fullName);

  cout << endl << "Enter units taking" << endl;
  cin >> info[1].units;
  cout << endl << endl;

  for(int i = 0; i < 2; i++)
    {
      cout << "STUDENT " << i + 1 << endl << endl;
      cout << "Student ID: " << info[i].studentID << endl;
      cout << "GPA: " << info[i].gpa << endl;
      cout << "Name: " << info[i].fullName << endl;
      cout << "Units: " << info[i].units << endl;
    }

  return 0;
}


I can't seem to solve why i get a seg fault
I can't seem to solve why i get a seg fault

What is the size of your array?

What are the valid index values of that array?

The problem is that you're accessing the array out of bounds.

If I am accessing an array out of bounds, how come each other line works perfect expect this specific one?
Undefined behaviour is undefined. Sometimes it can mean your program crashes. Sometimes it means some data gets corrupted in a way that doesn't crash your program. Sometimes it means that the program will appear to work.

If you write outside the bounds of the array, you will overwrite data at an address that may be being used for something else. You don't know what it's used for, and you don't know what the effect of overwriting it will be.

It's not really productive to worry about why the undefined behaviour manifests in a particular way, because that's down to the vagueries of your specific compiler. Just understand what you got wrong, and fix it.
Last edited on
Topic archived. No new replies allowed.