[solved] Program crashes when comparing two integers



  • I have the following small program:

    @#include <algorithm>
    #include <QDebug>

    QStringList list;

    bool comp(const QString &a, const QString &b) {
    qDebug() << a << b << list.indexOf(a) << list.indexOf(b);

    if (list.indexOf(a) <= list.indexOf(b)) {
        return true;
    }
    return false;
    

    }

    int main () {
    qDebug() << "begin";

    list << "I" << "II" << "III" << "IV" << "V" << "VI" << "VII"
       << "VIII" << "IX" << "X" << "XI" << "XII" << "XIII";
    
    QStringList list2;
    list2 << "V" << "III" << "III" << "IX"
      << "XII" << "XI" << "IV";
    std::sort(list2.begin(), list2.end(), comp);
    
    qDebug() << "end";
    
    return 0;
    

    }
    @

    When I compile it with MSVC2012 (Debug) I get the following output text:
    @begin
    "III" "V" 2 4
    "V" "III" 4 2
    "III" "III" 2 2
    "III" "III" 2 2 @

    and the following error window: http://postimg.org/image/ec2hnxzk5/ .
    In this window, If I press the Ignore button, the program somehow continues and after it closes, the output text is:
    @begin
    "III" "V" 2 4
    "V" "III" 4 2
    "III" "III" 2 2
    "III" "III" 2 2
    "IX" "III" 8 2
    "IX" "V" 8 4
    "XII" "III" 11 2
    "XII" "IX" 11 8
    "XI" "III" 10 2
    "XI" "XII" 10 11
    "XII" "XI" 11 10
    "XI" "IX" 10 8
    "IV" "III" 3 2
    "IV" "XII" 3 11
    "XII" "IV" 11 3
    "IV" "XI" 3 10
    "XI" "IV" 10 3
    "IV" "IX" 3 8
    "IX" "IV" 8 3
    "IV" "V" 3 4
    "V" "IV" 4 3
    "IV" "III" 3 2
    end@

    If I compile it with MinGW (Debug) it is the same situation, but the program crashes without displaying an error message.

    If I delete the following lines, the program runs without crashing:
    @if (list.indexOf(a) <= list.indexOf(b)) {
    return true;
    }@

    The program also runs without crashing when I build it in Release mode (either MinGW or MSVC2012).

    If I debug the program, I find the source of the error message in the source code (it seems related to the algorithm header.

    I really don't understand what is happening in that if condition and why the program doesn't work. I really need some help. Thank you!



  • Hi, it's because you're violating the contract with std::sort(), the comp() function should never return true when a and b are equal. (std::sort probably goes lost in your list and release mode is more forgiving)

    Try change the comparison to:
    @
    if (list.indexOf(a) < list.indexOf(b)) {
    return true;
    }
    @



  • I made the change you suggested and everything works as expected. Thank you!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.