vector

R

Rosario1903

why the below goes to seg fault?

#include <iostream>
#include <vector>
using namespace std;

void f(vector<unsigned>& v)
{v[3]=4; v[4]=9;}


int main(void)
{vector <unsigned> mv;

mv[0]=1; mv[1]=2;
f(mv);
cout<<"mv[0]="<<mv[0]<<", mv[1]="<<mv[1]<<"\n";
cout<<"mv[3]="<<mv[3]<<", mv[4]="<<mv[4]<<" mv[5]="<<mv[5]<<"\n";

return 0;
}
 
G

guinness.tony

why the below goes to seg fault?

#include <iostream>
#include <vector>
using namespace std;

void f(vector<unsigned>& v)
{v[3]=4; v[4]=9;}


int main(void)
{vector <unsigned> mv;

vector said:
mv[0]=1; mv[1]=2;
f(mv);
cout<<"mv[0]="<<mv[0]<<", mv[1]="<<mv[1]<<"\n";
cout<<"mv[3]="<<mv[3]<<", mv[4]="<<mv[4]<<" mv[5]="<<mv[5]<<"\n";

return 0;
}

When you declare a vector, with no construction arguments, it contains
exactly zero elements. Elements mv[0], mv[1], etc. do not yet exist.
This is why you get a seg-fault when trying to access them.

You can (as in my example, above) pre-allocate a number of
default-initialised elements. Or you can "manually" change the
size of the vector (using its resize() member function) or use
any of the insert()/push_back() member functions to add elements
to the vector.
 
K

K. Frank

Hello Rosario!

why the below goes to seg fault?
...
void f(vector<unsigned>& v)
{v[3]=4; v[4]=9;}
...
{vector <unsigned> mv;
mv[0]=1; mv[1]=2;
f(mv);

As guinne explained, vector mv starts off with no
elements, so you're accessing non-existent elements,
which can lead to a seg fault.

As a side note, for additional safety, you can access
elements using the "at" member function:

v.at(3)=4; v.at(4)=9;

"At" throws a std::eek:ut_of_range exception if the vector
doesn't contain the index being accessed. (For maximum
efficiency, "[]" doesn't perform this check.)


Good luck!


K. Frank
 
R

Rosario1903

Hello Rosario!

why the below goes to seg fault?
...
void f(vector<unsigned>& v)
{v[3]=4; v[4]=9;}
...
{vector <unsigned> mv;
mv[0]=1; mv[1]=2;
f(mv);

As guinne explained, vector mv starts off with no
elements, so you're accessing non-existent elements,
which can lead to a seg fault.

yes i thought that index allocate mem...
As a side note, for additional safety, you can access
elements using the "at" member function:

v.at(3)=4; v.at(4)=9;

thank you
"At" throws a std::eek:ut_of_range exception if the vector
doesn't contain the index being accessed. (For maximum
efficiency, "[]" doesn't perform this check.)


Good luck!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top