开发者

Stack Overflow Accessing Large Vector

开发者 https://www.devze.com 2022-12-27 21:53 出处:网络
I\'m getting a stack overflow on the first iteration of this for loop for (int q = 0; q < SIZEN; q++)

I'm getting a stack overflow on the first iteration of this for loop

for (int q = 0; q < SIZEN; q++)
{
    cout<<nList[q]<<" ";
}

nList is a vector of type int with 376 items. The size of nList depends on a constant defined in the program. The program works for every value up to 376, then after 376 it stops 开发者_开发知识库working.

Any thoughts?


If by "stops working", you mean crashes, then you're probably reading past the end of the buffer. vector::operator[] is not range checked, so it will let you shoot yourself in the foot.

If you want to traverse a vector, use an iterator, or at the very least nList.size().

So with least modifications to your code:

for (int q = 0; q < nList.size(); q++)
{
    cout << nList[q] << " ";
}

or with iterators

for (std::vector<int>::const_iterator it = nList.begin();
     it != nList.end(); ++it) {
  cout << *it << " ";
}


My initial guess here would be that the vector is less than 376. The [] operator makes no guaratees as to running over the actual vector bounds. You'd be much, MUCH safer if you used the at function:

for(int i=0; i < nList.size(); ++i){
  cout << nList.at(q) << " ";
}

there, if q is outside of the vector it'll throw an exception. That'll help diagnose this type of runtime problem.


If the you have added 376 elements to the vector by using for example push_back it is normal that the access with values higher than 376 make the program fail, you are accessing surely uninitialized and not managed memory.

0

精彩评论

暂无评论...
验证码 换一张
取 消