little007
little007

Reputation: 3

How did I get a segmentation fault here while using vectors in c++?

#include <bits/stdc++.h> 
using namespace std; 

int main() 
{
    vector<int> vect;
    vect[0]=1;
    vect[1]=1;
    vect[2]=1;

    for (int x : vect) 
        cout << x << " "; 

    return 0; 
}

I would like to know my fault here. I am new to c++ programming. Vectors is a very new concept to me.

Upvotes: 0

Views: 71

Answers (3)

Jose
Jose

Reputation: 3460

vect does not have allocated storage, so there isn't an arena to put the values on, hence undefined behaviour. You can get the allocated space of a container with capacity(), so in your case, vect.capacity() will return 0.

Furthermore, operator [] won't check the boundaries, so it will try to access to [ 2 ], even if its size is 0. To access checking boundaries use at().

Considering that, to solve the problem you will have to allocate space for the container (in your case, std::vector), that is, reserve an area of memory just for vect, vector offers different ways to modify its size, such as constructor, push_back, insert, resize, etc.

Note: if possible, avoid the use of using namespace std and <bits/stdc++.h>

Upvotes: 0

curiouscupcake
curiouscupcake

Reputation: 1277

You try to access the elements at the positions 1, 2, and 3 however they do not exist yet.

To insert to new element try the method push_back:

vect.push_back(1);
vect.push_back(1);
vect.push_back(1);

Another option is to create a vector with three zeros:

std::vector<int> vect(3, 0);
vect[0]=1;
vect[1]=1;
vect[2]=1;

Or much more simple, create a vector with size 3 and all elements are assigned with 1:

std::vector<int> vect(3, 1);

Upvotes: 1

cigien
cigien

Reputation: 60238

vect is an empty vector, so indexing into it invokes undefined behavior.

You could allocate enough space for vect, like this:

vector<int> vect(3);

Or you could push_back the elements:

vector<int> vect;
vect.push_back(1);
vect.push_back(1);
vect.push_back(1);

Upvotes: 3

Related Questions