Engine
Engine

Reputation: 5420

why this program is crashing

I wrote a small program in which, I want to set the value of a frame to 255 based on a vector:

result =    cv::Mat::zeros(frame.size(),CV_8UC1);
std::vector<cv::Point2f> imageCorners;
.......................................................
    for ( int i = 0 ; imageCorners.size();i++){
                std::cout << imageCorners[i]<< std::endl;
                result.at<uchar>(imageCorners[i]) = 255;
                cv::imshow("result",result);
            }

my question is: why the program crashes just after finishing the loop ?? even I see that result is correct ? the error message that I get is :

vector subscript out of range 

Upvotes: 0

Views: 128

Answers (4)

frkn
frkn

Reputation: 324

for ( int i = 0 ; imageCorners.size();i++)

I think this loop will run forever if imageCorners.size() is different than 0. So when this

std::cout << imageCorners[i]<< std::endl;

gets executed, at some point i will be out of bounds and the program will crash.

Upvotes: 0

w177us
w177us

Reputation: 332

The condition of your loop, imageCorners.size() only yields the number of elements stored in the container. The statement will always evaluate to true as soon as you put one element into imageCorners. What you want is i < imageCorners.size().

Upvotes: 1

piokuc
piokuc

Reputation: 26164

This looks dodgy to me:

 for ( int i = 0 ; imageCorners.size();i++){

you surely wanted to write something like:

 for ( int i = 0 ; i < imageCorners.size();i++){

Upvotes: 3

BoBTFish
BoBTFish

Reputation: 19757

for ( int i = 0 ; imageCorners.size();i++){
//                ^^^^^^^^^^^^^^^^^^^

The underlined part is the condition. In this case you are saying "keep looping until the size of imageCorners is "false" (i.e. 0)". But you never change the size of the vector, so this condition never stops the loop, i keeps getting bigger, until you try to access an index that isn't actually in imageCorners.

Presumably you mean to loop until i gets bigger than the vector. Then use

for (int i=0; i < imageCorners.size(); ++i) {

Upvotes: 4

Related Questions