Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Debug Assertion Failed Vector Subscript Out of Range C++

I am using VS2015 C++. I tried reading a file and inputing it line by line into a vector using a while loop.

I get this error:

Debug Assertion Failed!

Program: C:WindowsSYSTEM32MSVCP140D.dll

File: c:program files (x86)microsoft visual studio 14.0vcincludevector

Line: 1234

Expression: vector subscript out of range

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

My code is as follows:

int main() {
std::ifstream inf("walmart2.txt");

std::vector<std::string> blah;
int j = 0;

if (!inf) {
    std::cerr<< "Uh oh, walmart2.txt could not be opened for reading!" << std::endl;
    exit(1);
}
while (inf)
{
    std::string strInput;
    inf >> strInput;
    blah[j] = strInput;
    j = j + 1;
}

std::cout << blah.size() << '
';

return 0;
}

The file "walmart2.txt" is around 1800 lines in the following format:

53.74
54.09
53.5
53.72
53.43

I'm not entirely sure whats going on. Any help is appreciated.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
blah[j] = strInput;

This is undefined behaviour because blah is empty. Which means the compiler can make the program do anything.

When compiling with the right settings, Visual C++ makes use of that undefined behaviour in the C++ standard in order to actually detect the bug and show you this error message.

Fix the bug by using push_back instead:

blah.push_back(strInput);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...