-2

I tried sorting this array in ascending order and I got reply saying RUNTIME error(SIGSEGV). Can Anybody explain ?

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n, arr[1000];

    cin >> n;

    for (int i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    sort(arr, arr + n);

    for (int i = 0; i < n; i++)
        cout << arr[i] << endl;

    return 0;
}
0x4d45
  • 704
  • 1
  • 7
  • 18
  • 7
    What if `n` is greater than `1000`? – Yksisarvinen Jan 04 '20 at 16:50
  • 6
    Recommended reading: [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – HolyBlackCat Jan 04 '20 at 16:53
  • 7
    Why are you using `cin` and then `scanf`? Why not `cin` for both, given that you are writing C++ and not C. – walnut Jan 04 '20 at 16:54
  • 3
    What input did you use? – HolyBlackCat Jan 04 '20 at 16:54
  • 1
    `#include using namespace std;` - that combo is going to ruin your day at some point. The second bit can sometimes be ok, but the first is *never* ok and together they are *toxic*. – Jesper Juhl Jan 04 '20 at 17:28
  • 1
    If you just want to make it work, use `std::vector` as suggested by others. If you want to understand what SIGSEGV is and why you got one, study memory protection and virtual memory in operating systems ([Principles of Modern Operating Systems](https://www.amazon.com/Principles-Modern-Operating-Systems-Garrido/dp/1449626343) would be a good place to start). – 0x4d45 Jan 04 '20 at 17:49

2 Answers2

3

When you get input from a user that is used to populate an array, you should always validate the input before using it. If the user wants to enter 1001 numbers or more, or even a negative amount, you will access the array out of bounds and your program has undefined behaviour.

A better alternative is to use a std::vector to allocate just as much space as you need. One possible solution:

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

int main() {
    size_t n;

    if(std::cin >> n) {           // check that the user actually entered a number
        std::vector<int> arr(n);  // create a vector with n elements

        for(size_t i=0; i<n; ++i)
            std::cin >> arr[i];

        std::sort(std::begin(arr), std::end(arr));

        for(size_t i=0; i<n; ++i)
            std::cout << arr[i] << '\n';
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
1

You're allocating space for only 1000 elements, thereby causing segmentation fault if n is more than that, because scanf will try to put 1001-th element in memory location un-allocated to arr. Since you're using C++, Please use std:vector to avoid such pitfalls.

H S
  • 1,211
  • 6
  • 11