I need help with this following counting sort implementation. Is it because value of x can be too big? I am getting segmentation fault. This is what gdb says:
Program received signal SIGSEGV, Segmentation fault.
___chkstk_ms () at /usr/src/debug/gcc-5.4.0- 1/libgcc/config/i386/cygwin.S:146
146 /usr/src/debug/gcc-5.4.0-1/libgcc/config/i386/cygwin.S: No such file or directory.
And here is the code snippet,
void radix_sort::sort_array(int array[], int n)
{
int arrayB[n];
auto k = *std::max_element(&array[0], &array[n - 1]);
auto m = *std::min_element(&array[0], &array[n - 1]);
long int x = k - m + 1;
int arrayC[x];
for (auto i = 0; i < n; i++)
arrayC[array[i] - m]++;
for (long int i = 1; i < x; i++)
arrayC[i] = arrayC[i] + arrayC[i - 1];
for (auto i = n - 1; i >= 0; i--)
{
arrayB[arrayC[array[i] - m] - 1] = array[i];
arrayC[array[i] - m]--;
}
for (int i = 0; i < n; i++)
array[i] = arrayB[i];
}
int arrayB[n];
is non-standard C++ and in the GCC 4 and 5 implementation can easily result in a stack overflow ifn
is sufficiently large. Probably not your problem, but worth keeping an eye on. same again forint arrayC[x];
. Search keyword: "Variable Length Array" for more info. – Enhanced__chkstk_ms
is to intentionally generate a segfault when the array cannot fit on the stack. So yes,n
is too large. If you can't limit its value then you must use the new[] and delete[] operators instead. – Toboggan