Seg错误,可能的数组指针问题(基数排序实现)



我正在尝试对"随机"整数数组进行基数排序。radix_sort函数给了我分段错误。我检查了每个for循环,它们似乎都没有越界,所以我的假设是问题可能是数组指针,但我似乎无法在网上找到任何有助于解决此类问题的源信息。使用GCC编译,使用-std=c99标志

#include <stdio.h>
#include <stdlib.h>
#define LEN 1000
#define BYTES 4
#define BINS 256
void create_lst();
void int_radix_sort();
void radix_sort(int);
long data[LEN];
long temp[LEN];
int main(int argc, char * * argv) {
  create_lst();
  int_radix_sort();
  return 0;
}
void create_lst() {
  for (int i = 0; i < LEN; i++) {
    srand(rand());
    data[i] = rand();
  }
  return;
}
void int_radix_sort() {
  for (int i = 0; i < BYTES; i++) {
    radix_sort(i);
  }
  return;
}
void radix_sort(int byte) {
  long map[BINS], count[BINS];
  long *src_p, *dst_p;
  if((byte%2) == 0){
    src_p = data;
    dst_p = temp; 
  } else {
    src_p = temp;
    dst_p = data;
  }
  // Count
  for(int i = 0; i < LEN; i++)
    count[(src_p[i] >> (byte*8)) & (BINS-1)]++;
  // Map
  map[0]=0;
  for(int j = 1; j < BINS; j++)
    map[j] = count[j-1] + count[j-1];
  // Move
  for(int k = 0; k < LEN; k++)
    dst_p[map[(src_p[k] >> (byte*8)) & (BINS-1)]++] = src_p[k];
  return;
}

编辑:更多信息-当我通过调试器运行程序时,我发现问题是在最后一个循环(与K变量)

radix_sort中的count数组未初始化,其值用于在map中创建值,最后(参见// Move)用于索引dst_p,然后是BOOM。

在你修复初始化它们之后,你最终在map[1]中得到1954,这对于dst_p来说太大了,所以现在你正在寻找一个算法问题。尝试添加一些跟踪打印语句来解决您的问题。或者进入调试器(Linux上的gdb)并逐步执行程序,以验证所有步骤都如预期的那样。

for(int j = 1; j < BINS; j++)
    map[j] = count[j-1] + count[j-1];

是错误的。您希望map[j]保存前面插槽中元素的累积数量,因此应该为

for(int j = 1; j < BINS; j++)
    map[j] = map[j-1] + count[j-1];
         //  ^^^
         //  add the number of items in bin j-1 to the number of items in previous bins

最新更新