Eli Sadoff
Eli Sadoff

Reputation: 7308

Invalid Write Size using C++ Vectors at Address 0x0

I am working on bettering my knowledge in C++ and I wrote this program to try to work on vectors. The program itself is syntactically correct, but when I compile I get a SEG FAULT 11. So then I ran Valgrind on the code and I'm getting an invalid write size 4 error and also Address 0x0 is not stack'd, malloc'd or (recently) free'd. Here is my code

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

const int TTO = 2147483648;
int main()
{
    int n, s, p, q, i;
    cin >> n >> s >> p >> q;
    vector<int> a;
    a[0] = s % TTO;
    for(i = 1; i < n; i++)
        a[i] = (a[i-1]*p+q) % TTO;
    sort(a.begin(), a.end());
    a.erase(unique(a.begin(), a.end()), a.end());
    cout << a.size() << endl;
    return 0;
}

What can I do to have this not SEG FAULT?

Edit: The input I used was 3 1 1 1

Upvotes: 0

Views: 724

Answers (2)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133092

Your vector has no elements, so accessing even a[0] is illegal (more precisely, undefined behavior). Give your vector an initial size:

vector<int> a(n);
             ^^^

Upvotes: 3

Slava
Slava

Reputation: 44278

This:

vector<int> a;

creates an empty vector, so accessing any element (including 0) by operator [] is UB. Either call std::vector::resize() or add new elements by std::vector::push_back() or std::vector::emplace_back()

Upvotes: 2

Related Questions