Vineeth
Vineeth

Reputation: 11

Segmentation Fault , dynamically allocating a structure inside a dynamically allocated structure

Here is my complete code.... it's a big one,and thanks for your time.

https://pastebin.com/Uj97g357

In the code above I want to know the exact reason why I'm failing to dynamically allocate the memory for the structure inside a structure.I usually compete in codechef,hackerrank,codeforces.However,I'm new to doing some projects like these...I've debugged a bit so I've found where the mistake was,but I couldn't rectify it and I couldn't sleep peacefully...If you find the reason please let me know and Help me outcome it !!

In short my code is,for people who have less time to spare :) :-

struct subject
{
    struct DateTime StartTime,EndTime;   //Don't bother about these structure definitions
    string ClassName,ClassType;
    int ThresholdPercentage,MaxPossiblePercentage;
    struct Note notes;                  //Don't bother about these structure definitions
};
struct students
{
    struct subject *subjects;
    string name;
    int MaxSubjects;
} *student;

int main(void)
{
    int NStudents,Subjects,i,j;
    cout<<"Enter Number of Students:- ";
    cin>>NStudents;
    student=(struct students*)malloc(sizeof(struct students)*(NStudents+1));
    cout<<'\n';
    for(i=1;i<=NStudents;i++)
    {
        cout<<"Enter Number of Subjects for "<<i<<" Student:- ";
        cin>>Subjects;
        student[i].MaxSubjects=Subjects;
        student[i].subjects=(struct subject*)malloc(sizeof(struct subject)*(Subjects+1));   
        cout<<'\n';
        for(j=1;j<=Subjects;j++)
        {
            cout<<"Enter the name of Subject "<<j<<" :- ";

            cin>>student[i].subjects[j].ClassName;//<<<==================FAULT HERE.
        }
    PrintStudentSubjects(i);
    }
    return 0;
}

Actual Problem

    struct subject
{
    struct DateTime StartTime,EndTime;   //Don't bother about these structure definitions
    string ClassName,ClassType;
    int ThresholdPercentage,MaxPossiblePercentage;
    struct Note notes;                  //Don't bother about these structure definitions
};
struct students
{
    struct subject *subjects;
    string name;
    int MaxSubjects;
} *student;

student=(struct students*)malloc(sizeof(struct students)*(NStudents+1));
student[i].subjects=(struct subject*)malloc(sizeof(struct subject)*(Subjects+1));//<<== In a loop..

This gives me a Segmentation Fault...can't I use malloc?,If not why?..If yes,how come enlighten me :) .

Upvotes: 1

Views: 130

Answers (1)

Sid S
Sid S

Reputation: 6125

malloc() doesn't call the constructor for your classes. Use new.

student = new students[NStudents+1];
student[i].subjects = new subject[Subjects+1];

Upvotes: 1

Related Questions