Home > Mobile >  Segmentation fault in C adding item to a vector
Segmentation fault in C adding item to a vector

Time:05-02

Lately I have set myself to learn C , and while working on a bigger project, I have tried to use 'vectors'. But every-time I try passing it a value, it exits with a segmentation fault.

Here is my terminal output:

#include <iostream>
#include <vector>
using namespace std;
int main(){
    vector<int> test;
    cout << "hello world" << endl;
    test[0] = 0;
    return 0;
}
me@my-MacBook-Pro Desktop % g   test.cpp -o o && ./o
hello world
zsh: segmentation fault  ./o
#include <iostream>
#include <vector>
using namespace std;
int main(){
    vector<int> test;
    cout << "hello world" << endl;
   //test[0] = 0;
    return 0;
}
me@my-MacBook-Pro Desktop % g   test.cpp -o o && ./o
hello world
me@my-MacBook-Pro Desktop %

CodePudding user response:

The segfault is because of out of bound access. you need to set the size in the ctor

vector<int> test(1);

or push_back:

vector<int> test;
test.push_back(0);

CodePudding user response:

Size it vector<int> test = {0,1,2,3,4}; or vector<int> test(5)

But you might want to use push_back in this situation

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

    int main(){
    vector<int> test;
    cout << "hello world" << endl;
    test.push_back(0);
    cout << test[0];
    return 0;
}

Basically adds an item at the end.

Can also use maps with the keys be ints if you want to be able to just [] it or leave in spaces (which from what i saw is what your trying to do)

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

int main(){
    unordered_map<int, int> test;
    cout << "hello world" << endl;
    test[0] = 0;
    cout << test[0];
    return 0;
}
  • Related