2010-05-14 8 views
9

我正在使用合併排序的實現。我正在嘗試使用C++ Visual Studio 2010(msvc)。但是當我爲300000個整數計時時,它顯示一個未處理的堆棧溢出異常,並將我帶到名爲「chkstk.asm」的只讀文件。我把尺寸縮小到了200000,並且工作。再次相同的代碼與C-free 4編輯器(mingw 2.95)一起工作,而大小爲400000時沒有任何問題。您是否有任何建議讓代碼在Visual Studio中工作?對Visual C++中chkstk.asm的stackoverflow異常的建議

可能是mergesort中的遞歸導致了這個問題。

回答

10

問題解決了。感謝Kotti提供的代碼。與代碼相比,我遇到了問題。問題不在於遞歸太多。其實我正在處理一個正在存儲在堆棧上的普通C++數組。因此問題就出現在堆棧空間之外。我只是用new/delete語句將它改爲動態分配的數組,並且它工作正常。

+0

這解決了我的問題。謝謝。 +1 – 2012-04-17 04:24:54

5

我的猜測是,你有太多的遞歸,你只是用完堆棧空間。您可以使用linker's /F command line option來增加堆棧大小。但是,如果你保持堆棧大小限制,你可能想重構算法中的遞歸。

5

我不完全確定,但這可能是您的實現yor合併排序(導致堆棧溢出)的特定問題。有很多好的實現(使用谷歌),在VS2008以下工作與數組大小= 2000000

(你可以嘗試在VS2010)

#include <cstdlib> 
#include <memory.h> 

// Mix two sorted tables in one and split the result into these two tables. 
void Mix(int* tab1, int *tab2, int count1, int count2) 
{ 
    int i,i1,i2; 
    i = i1 = i2 = 0; 
    int * temp = (int *)malloc(sizeof(int)*(count1+count2)); 

    while((i1<count1) && (i2<count2)) 
    { 
     while((i1<count1) && (*(tab1+i1)<=*(tab2+i2))) 
     { 
     *(temp+i++) = *(tab1+i1); 
     i1++; 
     } 
     if (i1<count1) 
     { 
     while((i2<count2) && (*(tab2+i2)<=*(tab1+i1))) 
     { 
      *(temp+i++) = *(tab2+i2); 
      i2++; 
     } 
     } 
    } 

    memcpy(temp+i,tab1+i1,(count1-i1)*sizeof(int)); 
    memcpy(tab1,temp,count1*sizeof(int)); 

    memcpy(temp+i,tab2+i2,(count2-i2)*sizeof(int)); 
    memcpy(tab2,temp+count1,count2*sizeof(int)); 
    free(temp); 
} 

void MergeSort(int *tab,int count) { 
    if (count == 1) return; 

    MergeSort(tab, count/2); 
    MergeSort(tab + count/2, (count + 1) /2); 
    Mix(tab, tab + count/2, count/2, (count + 1)/2); 
} 

void main() { 
    const size_t size = 2000000; 
    int* array = (int*)malloc(sizeof(int) * size); 
    for (int i = 0; i < size; ++i) { 
     array[i] = rand() % 5000; 
    } 

    MergeSort(array, size); 
} 
+0

此代碼在Visual Studio 2010中正常工作,沒有任何問題。 – Gulshan 2010-05-14 17:59:46

+0

那麼,我想這意味着您在調用遞歸時填充堆棧方面的先前實現是無效的。我認爲您可以嘗試自己確定關鍵部件或在此處發佈代碼。 – 2010-05-14 18:06:28

+0

問題解決。看到我的答案。 – Gulshan 2010-05-17 12:08:35