Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program termination when trying to sort an array of objects

I have a class called ContactInfo and is structured as written below:

class ContactInfo
{
    private:
        string contactName;
        string contactNumber;

        public:
            ContactInfo()
            {
                contactName = "";
                contactNumber = "";
            }
            //setter and getters
};

and I have a function that creates an array of ContactInfo and populates it via user input. After populating the array it would be passed to another function that would sort it, the said function is written as shown below.

void sortListByName(ContactInfo contactList[], int listSize)
{
    for(int i = 0; i < listSize; i++)
    {
        for(int j = i+1; j < listSize+1; j++)
        {
            if(contactList[i].getContactName() > contactList[j].getContactName())
            {
                ContactInfo temp = contactList[j];
                contactList[i] = contactList[j];
                contactList[j] = temp;
            }

        }
    }
}

The main method

int main()
{
    ...

    int n;//array size
    ContactInfo *newList = contactList(n);//populates the array.
    sortListByName(newList, n);

    ...
}

The problem is that the program would terminate before the sorting would happen and produce the error:

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid
like image 723
Helquin Avatar asked Jan 24 '26 13:01

Helquin


1 Answers

Look at the upper bound of your inner loop. Notice that we can have j equal to the size of the array for the last iteration.

In C++, an array of size N has its elements indexed from 0 to N-1. In your case, you're trying to access an element past the end of the array, and are running into Undefined Behaviour. Ensure your index is within the bounds of the array.

Secondly, you should be using std::vector over raw arrays wherever possible anyways.

Third, the standard library provides the std::sort algorithm for you, which will almost always be faster than the bubble sort that you have implemented.

like image 137
Paul Belanger Avatar answered Jan 27 '26 03:01

Paul Belanger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!