-1

I'm trying to learn structures and I have a program which crashes for me - can't understand why. The compiler throws out a bad access exception when trying to access an element of an array of structures.

Here's the code:

#include <iostream>
#include <fstream>

FILE *input;

int n=1;
struct Student {
    string name;
    string city;
    int grades[4];
};
Student *students = new Student[n];

int main(int argc, const char * argv[]) {

input = fopen("input.txt", "r");
if(input==NULL) {
    cout<<"\nCan't open file input.txt";
    return;
}

int size;
if(fscanf(input, "Size%d\n\n",&size)<=0) {
    cout<<"\nAn error occurred.";
    return;
}
n=size;
cout<<"\nThe size is "<<n;
for(int i=0;i<n-1;i++) {
    Student newStud;
    char name[255];
    char city[255];
    fscanf(input, "\n%s\n%s\n%d;%d;%d;%d;",name,city,&newStud.grades[0],&newStud.grades[1],&newStud.grades[2],&newStud.grades[3]);
    newStud.fullName = name;
    newStud.city = city;
    cout<<"\nAdding student at "<<i;
    students[i]=newStud;
    cout<<"\nAdded successfully";
}
fclose(input);

cout<<"\nLoad complete!";
}

input.txt:

Size5

Bob
NY
10;10;10;10;
Rick
SF
6;6;6;6;
John
NY
2;3;2;5;
Jack
NY
5;5;5;4;

Console output:

The size is 5
Adding student at 0
Added successfully
Adding student at 1
BotistSab
  • 31
  • 1
  • 6
  • Compile with all warnings and debug info (e.g. `g++ -Wall -Wextra -g` with [GCC](http://gcc.gnu.org/)...). Improve the code to get no warnings. **Use the debugger** (e.g. `gdb`) to understand what is happening inside your program. – Basile Starynkevitch Dec 10 '17 at 15:07
  • 1
    Urgently recommended read: https://stackoverflow.com/questions/46991224/are-there-any-valid-use-cases-to-use-new-and-delete-raw-pointers-or-c-style-arr – user0042 Dec 10 '17 at 15:08
  • 2
    Since `n` is `1`, at the time of array allocation - the array contains only a single `Student`, and when you try to access the second element of an array - you are invoking undefined behavior due dereference of unallocated memory. – Algirdas Preidžius Dec 10 '17 at 15:08

2 Answers2

1

The initialization of the students pointer is done before the execution of main. You wouldn't have read n by then. Therefore, your code ends up allocating memory for 1 Student in students array.

The code in your main assumes that the students array is capable of holding size (or the current value of n) while it isn't really the case. Hence, the code ends up accessing unknown locations which causes undefined behavior (a segmentation fault almost always).

The fix is to allocate memory for the array after the input for n has been taken.

Yashas
  • 1,154
  • 1
  • 12
  • 34
0

Obviously,the program crashed when you tried to access the second Student in the array while you only allocated one size of the Student for it. You should allocate the array’s memory after the code “n = size” but not before,which you did at the top of the main entrance is absolutely unreasonable for your purpose.