-2

Window 64bit
gcc 6.3.0
vscode

#include <algorithm>
#include <iostream>

using namespace std;

bool compare(int a, int b) {
    return a <= b;
}

int main() {
    int N;
    cin >> N;

    int *arr = new int(N);

    for (int i = 0; i < N; i++) {
        cin >> arr[i];
    }

    sort(arr, arr + N - 1, compare);

    for (int i = 0; i < N; i++) {
        cout << arr[i] << '\n';
    }
}

First version of my code was sort(arr,arr+N,compare)
but it seems like there might be a possibility of trasspassing for unallocated memory, so I changed it to arr+N -> arr+N-1
still facing the Segmentation fault

I'd like to know why this error occurs

jadon
  • 29
  • 4

2 Answers2

0

Took the comments from thesturgler and made this

#include <algorithm>
#include <iostream>

using namespace std;

bool compare(int a, int b) {
    return a <= b;
}

int main() {
    int N = 0;
    cin >> N;

    if (N < 1) return 1;

    int *arr = new int[N];

    for (int i = 0; i < N; ++i) {
        cin >> arr[i];
    }

    sort(arr, arr + N, compare);

    for (int i = 0; i < N; ++i) {
        cout << arr[i] << '\n';
    }
    delete [] arr;
    return 0;
}

added an error check on N value and return statements.

dex black
  • 36
  • 6
0

It may depends on your compiler, but i made minor changes to your code to fix potential issues. I used -std=c++11 and -std=c++14 in VS and got no error. list of changes;

  1. new int(N). ---> new int[N]

  2. sort(arr, arr + N-1, ... --> sort(arr, arr + N ,...

  3. for sort you can also remove the compare method as well, unless you want to sort in different way.

  4. sort(arr, arr+ N-x) or sort(arr, arr+ N-x, compare) --> they will sort only first N-x elements of the array.

  5. delete is missed, in C++ for any new you should have a delete pair. This is small example, but in larger scale codes or whenever you have memory concern, it may causes some issues. You can deallocate the memory like "delete[] arr" for arrays. More details

#include <algorithm>
#include <iostream>
using namespace std;

bool compare(int a, int b) {
    return a <= b;
}

int main() {
    int N;
    cin >> N;

    int *arr = new int[N];

    for (int i = 0; i < N; i++) {
        cin >> arr[i];
    }

    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
    cout<<"\nafter sorting will be\n";
    
    //sort(arr, arr + N);
    sort(arr, arr+N-1, compare);
    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
    delete[] arr;
    cout<<endl;
    return 0;
}
Ashkanxy
  • 2,380
  • 2
  • 6
  • 17