Егор Лебедев
Егор Лебедев

Reputation: 1336

Why there is segmentation fault?

Hi I just start learning c++ and come with strange behavior.

here is code

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

long long MaxPairwiseProduct(const std::vector<long long>& numbers) {
    int n = numbers.size();
    int fidx, sidx = 0;

    for (int i = 1; i < n; ++i) {
        if (numbers[i] > numbers[sidx]) {
            fidx = sidx;
            sidx = i;
        } else if (numbers[i] > numbers[fidx]) {
            fidx = i;
        }
    }
    return numbers[fidx] * numbers[sidx];
}

int main() {
    int n;
    std::cin >> n;
    std::vector<long long> numbers(n);
    for (int i = 0; i < n; ++i) {
        std::cin >> numbers[i];
    }

    std::cout << MaxPairwiseProduct(numbers) << "\n";
    return 0;
}

I compile it with g++ -pipe -O2 -std=c++11 max_pairwise_product.cpp and then put in input this:

2
100000 90000

and it throws Segmentation fault (core dumped) but when I add std::cout << sidx << fidx << std::endl; before calculate result of maxPairwiseProduc it compiles and works as it should, providing right result. Actually it will work even if I put just std::cout << ""; So what is happened here? and how I could debug such cases to understand what is going on?

Upvotes: 0

Views: 82

Answers (1)

Егор Лебедев
Егор Лебедев

Reputation: 1336

int fidx, sidx = 0;

fidx here is not initialized, that cause undefined behavior, so it can sometimes work, sometimes not, need to be something like

int fidx = 0;
int sidx = 0;

Here is a article with different ways of initializing variables in c++ link

Upvotes: 2

Related Questions