Shahid Nagra
Shahid Nagra

Reputation: 3

Getting Runtime Error(SIGSEGV) on Hackerearth, can't find out what's wrong in code

I know its a invalid memory reference error, but I can't seem to find the cause of the error in my code.

I just tried my problem on Hackerearth, it was the 'Find Product' https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/find-product/ and my submission was this, which gave me no errors on codeblocks compiler, but pops a Runtime Error(SIGSEGV).

#include <iostream>

using namespace std;

int main() {
  int cases;
  int pro = 1;
  int product[1][cases];
  cin >> cases;
  for (int x = 0; x < cases; x++) {
    cin >> product[1][x];
  }
  for (int x = 0; x < cases; x++) {
    pro *= product[1][x];
  }
  cout << pro;
}

Thanks in advance :)

Upvotes: 0

Views: 502

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

  • Your int product[1][cases]; is before cin >> cases;, so the input will not be used for allocation.
  • You declared int product[1][cases];, so only product[0] is allowed and using product[1] is out-of-range (invalid).
  • Variable-length array is not in C++ standard.

Try this:

#include <iostream>

using namespace std;

int main() {
  int cases;
  int pro = 1;
  cin >> cases;
  int* product = new int[cases];
  for (int x = 0; x < cases; x++) {
    cin >> product[x];
  }
  for (int x = 0; x < cases; x++) {
    pro *= product[x];
  }
  cout << pro;
  delete[] product;
}

Upvotes: 1

Related Questions