-2

When I try to input to vector by following code, I get a segmentation fault as shown below. I defined the vector and set N, and tried to input a vector with N elements. What is the root cause of this?

#include <iostream>
#include <vector>

using namespace std;
int N;
vector<int> A(N);
int main(){
    cin>>N;
    for(int i=0;i<N;i++) cin>>A[i];
}
[ec2-user@ip-10-0-1-187 ]$ ./vector_input 
1
1
Segmentation fault
codeling
  • 11,056
  • 4
  • 42
  • 71
Heisenberg
  • 4,787
  • 9
  • 47
  • 76
  • 1
    You need to declare or resize the vector *after* you've read `N`. Right now, since `N` is a global variable it is initialized to 0, so the size of the vector is 0. You could also read the data into a temporary variable and use `A.push_back(temp);` to add it to the end of the vector. – Retired Ninja Apr 27 '22 at 10:49
  • Correct is to always check result of every operation with input stream because the input data can come from either dumb or evil user or from program written by dumb or evil programmer. – Öö Tiib Apr 27 '22 at 11:57

3 Answers3

3

That's because constructor of A is called with N=0. When you input N, it doesn't affect the vector at all. If you really want to keep using globals, then use std::vector::resize but the recommended way would be:

int main(){
    std::size_t n;
    std::cin >> n;
    std::vector<int> A(n);
    for(auto & x : A) std::cin >> x;
}
Staz
  • 348
  • 1
  • 2
  • 6
  • The code in the question does **not** call the vector constructor with `N=0`, it calls it with an unitialized `N`! This could be any random value previously in there. – codeling Apr 28 '22 at 06:03
  • @codeling `N` is static in the given code and therefore it'll be initialized to `0`, not garbage. (https://en.cppreference.com/w/cpp/language/zero_initialization) – Staz Apr 28 '22 at 07:38
  • ah, missed that, yes, thanks for the clarification! the wonders of c++ initialization ;) – codeling Apr 28 '22 at 09:14
1

This happened because N was never initialized and it was used for initiating vector. So, your code produces undefined behavior.

You need to take input first, and then initialize the vector. Also, avoid using using namespace std;. And there's no real need to initialize A and N in a global scope.

NOTE: To avoid undefined behavior further you enable this flag while compiling C++ programs.

-fsanitize=undefined,address

Code:

#include <vector>
#include <iostream>

int main(void)
{
    int N;
    std::cin >> N;
    std::vector<int> A(N);
    for(auto &i : A)
        std::cin >> i;
    return 0;
}
Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23
0

The variable N used for initialization is not initialized

int main(){
    int n,a;
    vector<int> vec;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> a;
       vec.push_back(a);
    }
}