我尝试运行以下快速排序算法,并在使用 gdb 调试它时收到以下错误:
程序收到信号SIGSEGV,分段错误。
分区中的0x000055555555530a (arr=
, low= , 高=
源代码是:
/* This program in C demonstrates the quick sort algorithm in C
* For partitioning I have used the Hoare's algorithm via using the
* first element of the array as the pivot element
*/
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#define true 1
void swap(int*, int*);
void quick_sort(int arr[], int, int);
int partition(int arr[], int, int);
void print_array(int arr[], int);
int main(int argc, char* argv[])
{
int array[10] = {3, 4, 2, -1, 7, 100, 82, 5};
int size = sizeof(array) / sizeof(array[0]);
print_array(array, size);
quick_sort(array, 0, size - 1);
print_array(array, size);
return 0;
}
void print_array(int arr[], int size)
{
printf("The array for quick sort algorithm\n");
for (int i = 0; i < size; i++) {
printf("%d\t", arr[i]);
}
}
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
/* This function returns the pivot postion, initially the pivot is set to the first element */
int partition(int arr[], int low, int high)
{
int pivot = arr[low];
int i = low - 1;
int j = high + 1;
while (true) { /* Till the loop is infinitely running */
do {
i++;
}while (arr[i] <= pivot);
do {
j--;
}while (arr[j] > pivot);
if (i >= j) /* Once there is crossover, return j */
return j;
swap(&arr[i], &arr[j]);
}
}
void quick_sort(int arr[], int low, int high)
{
if (low < high) { /* If there are atleast 2 elements in the array */
int pivot_pos = partition(arr, low, high);
quick_sort(arr, low, pivot_pos);
quick_sort(arr, pivot_pos + 1, high);
}
}
这也是 gdb 布局,它显示了源代码和 asm。
问题出在这一行:
}while (arr[i] <= pivot);
如果没有元素大于枢轴,则
i
将继续越界。
如果没有对指针
i
和j
进行边界检查,那么必须使用严格比较来避免这种情况:
}while (arr[i] < pivot);