K
K
kernel_Pan1c2021-09-27 22:50:25
C++ / C#
kernel_Pan1c, 2021-09-27 22:50:25

Segmentation error (memory stack flushed to disk) c++. How to fix?

There is an error in this code snippet. I just can't understand what's the matter.
The program itself must return a binary sequence of length n

#include <iostream>
#include <vector>

using namespace std;

void func(int a, vector<int>& v1){
  if(a == v1.size()){
    for(int i = 0; i < v1.size(); ++i){
      cout << v1[i];
    }
    cout << endl;
    return;
  }
    for(int i = 0; i < v1.size(); ++i){
      v1[a] = i;
      func(i + 1, v1);
    }
  
}

int main(){
  int n;
  cin >> n;
  vector<int> v;
  for(int i = 0; i < n; ++i){
    v.push_back(0);
  }
  for(int i = 0; i < n; ++i){
    cout << v[i];
  }
  func(1, v);
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-09-27
@wataru

Your program endlessly recurses, runs out of memory, and crashes. func(1, v) in the loop for i=0 will call func(1,v1), which again will call func(1,v1), which again... And so on until the program gets sick.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question