Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

c++ - Vector iterator not dereferencable error when trying to push_back()

I have a problem when my application crashes with this error message from VS: "Debug assertion failed! (...) Expression: vector iterator not dereferencable".

The thing is, it happens during using vector's push_back.

Here is the code. It is my BigInt library, that I decided to implement as an exercise. The bug is hidden in my TestBigInt class, that I created to (surprisingly) test BigInt. The code is admittedly quite long, but I narrowed the bug to a single piece of that. This is the input I give to the bugged code:

/* "BigIntTestCases.txt": format { label num1 num2 autoChecked { } }
* { 1 3 2 1 { } }
* { 2 10 7 1 { } }
* { 3 21 9 1 { } }
* ...
*/
    int main() {
        ifstream ifs{ "BigIntTestCases.txt" };
        // read tests into vector<BigIntTest>
        for (auto it = tests.begin(); it != tests.end(); ++it) {
            std::cout << "Read: " << it->label << ' ' << it->num1 << ' ' << it->num2 << ' ' << it->autoChecked << '
';
            performTest(ofs, (*it));
        }
    }

That gives me output:

Read: 1 3 2 1
pushed_back exResults
pushed_back outResults
Read: 2 10 7 1
pushed_back exResults
CRASH

This is "TestBigInt.cpp", and here lies the bug (in the first 4 push_backs of the first function - doTests()):

void TestBigInt::doTests()
{
    // fill outResults - vector of BigInt test results
    BigInt firstNum{ num1 };
    BigInt secNum{ num2 };

    outResult.push_back((firstNum + secNum).toString());
    outResult.push_back((secNum + firstNum).toString());
    outResult.push_back((firstNum - secNum).toString());
    outResult.push_back((secNum - firstNum).toString());
    outResult.push_back((firstNum * secNum).toString());
    outResult.push_back((secNum * firstNum).toString());
    std::cout << "pushed_back outResults
";
}
void TestBigInt::autoFillExR()
{
    // fill vector exReults -- expected results
    int firstNum = stringToI(num1);
    int secNum = stringToI(num2);

    exResult.push_back(iToString(firstNum + secNum));
    // ... - essentialy the same as doTest()
    std::cout << "pushed_back exResults
";
}
std::ostream& performTest(std::ostream& os, TestBigInt& t)
{   
    if (t.autoChecked) // if the results are to be autochecked, than fill the exResult -- else it is already full
        t.autoFillExR();

    t.doTests();

    for (auto itE = t.exResult.cbegin(), itO = t.outResult.cbegin(); itE != t.exResult.cend() && itO != t.outResult.cend(); ++itE, ++itO)
        if (*itE != *itO)
            os << "Test not passed: " << t.label  << ", " << distance(t.exResult.cbegin(), itE) << "
	Expected: " << *itE << ", got " << *itO << "
";

    return os;
}

This is implementation of BigInt::toString

std::string BigInt::toString() const
{
 // the digits are stored in "reversed order", i.e. digits[0] is the least significant digit
    std::string num;
    if (sign == Sign::negative)
        num += "-";
    for (auto it = digits.crbegin(); it != digits.crend(); ++it)
        num += ('0' + *it);
    return num;
}

I do know that it is extremely long sample, but at least I narrowed the bug by quite a bit. Frankly I have no idea why it does not work.

A big thank you to anyone that read through this post. If you have any ideas about why it could be wrong, than please do post it here -- I'm quite helpless, and would appreciate any help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't iterate through a vector while pushing back, as push_back may invalidate iterators.

I can't see the problem mentioned here above in the posted code though (refer code), hence I retract the answer above. I've based it on assumptions prior to seeing all the code.

However, given this code:

for (TestBigInt t; ifs >> t; )
        tests.push_back(t);

Are you aware that you are always modifying the same instance of t. You are pushing copies, but operator >> always modifies the original instance, growing its vector. Is this what you want? Your amount of results then exceed 6...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...