0

I'm creating class Student, and I'm getting an error: program has triggered a breakpoint on operator[]. Please help me and show what's wrong, and what is missing.

Fixed:

#include "stdafx.h"
#include <iostream>

class Student {
public:
    Student();
    ~Student();
    void Show();
private:
    char* Name;
    char* Surname;
    char* DateOfBirth;
    unsigned long PhoneNumber;
};

Student::Student() {
    Name = nullptr;
    Surname = nullptr;
    DateOfBirth = nullptr;
}

Student::~Student() {
    if (Name != nullptr) delete[] Name;
    if (Surname != nullptr) delete[] Surname;
    if (DateOfBirth != nullptr) delete[] DateOfBirth;
}

void Student::Show() {
    std::cout << Name << " " << Surname << "\t" << DateOfBirth << "\t" << PhoneNumber << std::endl;
}

class StudentGroup {
public:
    StudentGroup();
    ~StudentGroup();
    void Add(char* Name, char* Surname, char* DateOfBirth, unsigned long PhoneNumber);
    Student& operator[](int index); 
private:
    Student* stud;
    int length;
};

StudentGroup::StudentGroup() {
    length = 0;
    stud=nullptr;
}

StudentGroup::~StudentGroup() {
    delete[] stud;

}

void StudentGroup::Add(char* Name, char* Surname, char* DateOfBirth, unsigned long PhoneNumber)
{
    Student* stud1; 
    stud1 = new Student[length+1];
    for (int i = 0; i < length; i++)
        stud1[i] = stud[i];
    delete [] stud;
    stud = stud1;   
    stud[length].SetName(Name);
    stud[length].SetSurname(Surname);
    stud[length].SetDateOfBirth(DateOfBirth);
    stud[length].SetPhoneNumber(PhoneNumber);
    length++;
}

Student& StudentGroup::operator[](int index) {
    return stud[index];
}

int _tmain(int argc, _TCHAR* argv[])
{
    setlocale(LC_CTYPE,"Russian");
    StudentGroup students;
    students.Add("Ivan","Ivanov","2010-01-01",234234422);
    students.Add("Petr","Petrov","2012-01-01",365753663);
    students[0].Show();
    return 0;
}
jsmith
  • 175
  • 1
  • 10

2 Answers2

1

drescherjm is correct in the comments.

Your constructor doesn't initialize StudentGroup::stud, so when you attempt to increase the size of it you call delete [] <uninitialized_pointer>.

To fix this, you should have:

StudentGroup::StudentGroup() {
    stud = nullptr;
    length = 0;
    nextIndex = 0;
}
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
0

You struct student has pointers, exactly 3 pointers!

It is obvious calling delete[] stud; without handling deletion of char* Name, char* Surname and char* DateOfBirth members of each student object, leads to HEAP CORRUPTION ERROR

Ali Razmkhah
  • 280
  • 1
  • 10