Search code examples
c++crashbinary-treeprogram-entry-point

'main' has stopped working - C++ [dev++]


My code is behaving really weird. It works sometimes and it crashes at other times.

When it crashes it says:

a problem caused the program to stop working correctly

My main:

int main() {
    start();
    Read();

    cout << "Enter the code of the course: ";
    cin >> coursecode;
    cout << "\n1111111\n";
    searchCourse(coursecode);
    cout << "\n222222\n";

    return 0;
}

I wrote two couts above and below my searchCourse function to see if the program compiles all the lines. It really does compile everything, and at the end it prints 222222 before crashing.

The start method just creates an array of BinaryTree objects then store the student data (they are read from text file) according to their courses.

start():

BinaryTree *a[10];

void start()
{
    for(int g=1;g<=10;g++)
    {
        a[g] = new BinaryTree(g);
    }
}

searchCourse():

void searchCourse(string code)
{
    for(int j=1;j<=count;j++)
    {
        if(a[j]->checkit(code)!=0)
        {
            a[j]->display();

            break;
        }
    }
}

Checkit() in BinaryTree.h:

bool checkit(string m)
{
    if (root==NULL)
        return false;
    else
        if(root->data.getCourse()==m)
            return true;
        else
            return false;
}

Solution

  • BinaryTree *a[10];
    for(int g=1;g<=10;g++)
    {
        a[g] = new BinaryTree(g);
    }
    

    Would have a memory exception. You have an array of 10, and you are trying to access the 11th element (since you go until g<=10, and a[10] is the eleventh element). Use:

    for(int g=0;g<10;g++)
    

    instead. You may have to also do new BinaryTree(g+1); if Binary Tree starts at 1.

    This is an error that is in other places in your code as well, like for(int j=1;j<=count;j++) (for(int j=0;j<count;j++) is probably what you want).

    Arrays start at 0. Why does the indexing start with zero in 'C'?