2016-08-18 29 views
1

即使在我爲包含1000萬條目的數組動態分配空間後,以下代碼在4Gb計算機上運行時也會出現分段錯誤。它可以正常工作,有100萬個條目,即n = 1000000.下面的代碼使用基數排序將整數值及其索引值排序。我應該做些什麼來使這個計劃適用於1000萬條記錄。帶有堆分配的大尺寸陣列上的分段錯誤

int main() 
{ 
    int n=10000000; // 10 million entries 
    int *arr=new int [n]; // declare heap memory for array 
    int *arri=new int [n]; // declare heap memory for array index 

    for(int i=0;i<n;i++) // initialize array with random number from 0-100 
     { 
      arr[i]=((rand()%100)+0); 
     } 

    for(i=0;i<n;i++) // initialize index position for array 
     { 
      arri[i]=i; 
     } 

    radixsort(arr, n ,arri); 
    return 0; 
} 

// The main function to that sorts arr[] of size n using Radix Sort 
void radixsort(int *arr, int n,int *arri) 
{ int m=99; //getMax(arr,n,arri); 

    // Find the maximum number to know number of digits 


    // Do counting sort for every digit. Note that instead 
    // of passing digit number, exp is passed. exp is 10^i 
    // where i is current digit number 
    for (int exp = 1; m/exp > 0; exp *= 10) 
     countSort(arr, n, exp,arri); 


} 

void countSort(int *arr, int n, int exp,int *arri) 
{ 
    int output[n],output1[n]; // output array 
    int i, count[10] = {0}; 

    // Store count of occurrences in count[] 
    for (i = 0; i < n; i++) 
     { 
      count[ (arr[i]/exp)%10 ]++; 

     } 

    // Change count[i] so that count[i] now contains actual 
    // position of this digit in output[] 
    for (i = 1; i < 10; i++) 
     count[i] += count[i - 1]; 

    // Build the output array 
    for (i = n - 1; i >= 0; i--) 
     { 

      output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; 
      output1[count[ (arr[i]/exp)%10 ] - 1] = arri[i]; 
      count[ (arr[i]/exp)%10 ]--; 
     } 

    // Copy the output array to arr[], so that arr[] now 
    // contains sorted numbers according to current digit 
    for (i = 0; i < n; i++) 
     { 
      arr[i] = output[i]; 
      arri[i]=output1[i]; 
     } 

} 
+0

「countSort」中的數組未被動態分配。 – Barmar

+0

請注意,變長數組不是標準的C++。它們在C中,你的編譯器允許它們作爲擴展。 – Barmar

回答

2

問題出在countSortoutputoutput1數組是本地數組,不是動態分配的,它們對於局部變量來說太大了。您還使用可變長度數組的C特性,它不是標準C++的一部分。他們更改爲:

int *output = new int[n]; 
int *output1 = new int[n]; 

,在函數的末尾添加

delete[] output; 
delete[] output1; 

+0

代替使用'std :: vector'更好。讓它爲你管理記憶。 –

+0

或者,也許,根據平臺和工具鏈,設置適當的鏈接器標記以預留足夠的堆棧空間以容納本地陣列。 – dxiv

+0

@RemyLebeau我不想重新設計這個程序,只是簡單地修復他的錯誤。他認爲他沒有使用本地陣列,他錯過了這個地方。 – Barmar