快速排序的实现中size_t的问题

时间:2019-05-03 19:39:42

标签: c segmentation-fault quicksort sigsegv

我决定实施一种快速排序算法。有时,程序正常运行。有时,由于细分错误而导致。

gdb消息:

Program received signal SIGSEGV, Segmentation fault.
0x0000555555554de4 in __partition__ (array=0x555555757260, index_low=0, 
    index_hight=18446744073709551615)
    at /home/dosart/Programing_Language/C/Sort/src/QuickSort.c:37
    if(array[i] <= key)

int 替换 size-t 可解决此问题。为什么?

typedef ELEMENT int;

static void __quick_sort__(ELEMENT *arr, size_t index_low, size_t index_hight)
{
  size_t m = 0;
  if (index_hight > index_low)
  {
      m = __partition__(arr, index_low, index_hight);
    __quick_sort__(arr, index_low, m - 1);
    __quick_sort__(arr, m + 1, index_hight);
  }
}

static size_t __partition__(ELEMENT *array, size_t index_low, size_t index_hight)
{
  ELEMENT key = array[index_low];
  size_t j = index_low;

  for (size_t i = index_low + 1; i <= index_hight; ++i)
  {
    if(array[i] <= key)
    {
      j = j + 1;
      swap(&array[j], &array[i], sizeof(ELEMENT));
    }
  }
  swap(&array[index_low], &array[j], sizeof(ELEMENT));
  return j;
}

void swap(void *x, void *y, size_t size)
{
  char tmp;
  size_t i = 0;

  while (i < size)
  {
    tmp = *((char*)x + i);
    *((char*)x + i) = *((char*)y + i);
    *((char*)y + i) = tmp;
    i++;
  }
}

0 个答案:

没有答案