Here is some debugging output. Everything I typed is in bold.
(gdb) run
Starting program: ./a.exe
[New thread 1252.0x11b4]
How many questions will be asked?
2
Enter the answer for question 1[A,B,C,D]:
A
Enter the answer for question 2[A,B,C,D]:
B
Enter the number of students to test:
2
Enter the name of student 1:
Eric
Enter the answer for question 1:
Eggs
Enter the answer for question 2:
Enter the name of student 2:
Enter the answer for question 1:
Bill
Enter the answer for question 2:
Eric was correct on the following questions:
Program received signal SIGSEGV, Segmentation fault.
0x004018c4 in main () at 39.cpp:65
65 cout << "for a total of " << numCorr[k] << " answers." << endl; //total correct answers
(gdb) print k
$1 = 0 |
There is an attempt to access element 0 of
numCorr. Since you create
numCorr and then never make it big enough to have any data put into it, it's not surprising that trying to fetch data from it causes a segFault.
I note also that on some requests for data, I was unable to enter anything as the programme skipped straight on to the next section without waiting for me to enter anything. I suspect because I entered a word of four letters (Eggs) rather than a single letter. When you get it all working, it's worth defending against that.
I can also provoke a segFault by entering different data, with the segFault on this line:
60 numCorr[k] += 1; //counter
It's the same problem as before. Trying to put something into numCorr[0] which does not exist. You've hit this same problem repeatedly, which suggests you're misapprehending vector containers.
When you create a vector container, like this:
vector<char> corrAns;
it has no size. It is of size zero. Attempting to put something into or read something from any element will cause a segfault. If you wish to actually use it, you must increase its size. You can do this with the
resize class method.
push_back works because the
push_back method will automatically resize the vector as needed before adding the data.