Runtime Error while iterating over a vector using for loop

My question is pretty straightforward.
Why is it so that while iterating over an “EMPTY” vector using “for” loop leads to a runtime error.

A simple example would be:

vector<int> v;
cout << v.size() << endl;
for( int i = 0; i < v.size(); i++ )
 cout << v[i] << " ";

The thing is even though “v.size()” returns a 0, a SIGSEGV error occurs.
This is strange in the fact that the for loop should never be executed so there is no question about accessing anything out of the bounds.

I know this can be easily resolved by using vector<int>::iterator, but still why’s this problem with for loop ?

Any help would be appreciated.
Thanks.

Hello nellex,

I have been using vector and stl based container from a long time but i have not come across any such situation throughout the period. I am damm sure you must be something wrong… else this is perfectly valid and works accordingly …

int main(){

vector<int> A ;
for(int i=0;i<A.size();i++){
	cout << A[i] << endl ;
}
cout << "Ma5termind" << endl ;
return 0 ;

}

this fragment of code is perfectly valid and will not produce any kind of runtime error …

you can also look for the execution of this simple code …

1 Like

It doesn’t. The runtime error must come from somewhere else.

Hey thanks for the reply, then can you please explain me as to why my submission http://codeforces.com/contest/501/submission/9413063 fetched a Runtime error for an empty vector and when i just replaced the for loop with vector iterator got an AC http://codeforces.com/contest/501/submission/9415300.