Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a vector as argument and using it, why does it crash?

I'm fairly new to C++ especially STL. I'm trying to pass a vector as argument to a function, but it causes the application to crash. I'm using Code::Blocks and MingW. Here is a simple code.

#include <iostream>
#include <vector>

using namespace std;

void foo(const vector<int> &v)
{
    cout << v[0];
}
int main(){
    vector<int> v;
    v[0] = 25;
    foo(v);
return 0;
}

Thanks!

like image 550
Physer Avatar asked Aug 03 '12 17:08

Physer


1 Answers

It crashes because you write past the end of the vector with v[0] - that's undefined behaviour. Its inital size is 0 if you do nothing. (You subsequently read the same too, but all bets are off well before that point).

You probably wanted to do:

vector<int> v;
v.push_back(25);
foo(v);

Or maybe:

vector<int> v(1);
v.at(0) = 25;
foo(v);

If you use v.at(n) instead of the [] operator you will get exceptions thrown rather than undefined behaviour.

like image 54
Flexo Avatar answered Oct 13 '22 00:10

Flexo