2014-11-06 60 views
0

我正在嘗試編寫一個C程序來獲取離散正整數的數組,並查找最長增長子序列的長度。C搜索功能中的分段錯誤(核心轉儲)錯誤

'詮釋* a' 是隨機產生的整數數組,這是長度的 '詮釋B'

呼叫: lis_n = answer(seq, seq_size);

功能:

int answer(int* a, int b) { 
    if (a == NULL) {return -1;} 
    int i = 0; 
    int j = 0; 
    int k = 0; 
    //instantiate max and set it to 0 
    int max = 0; 
    //make an array storing all included numbers 
    int included[b]; 
    memset(included, 0, b*sizeof(int)); 
    //create a pointer to the index in included[] with the largest value 
    int indexMax = 0; 
    //create a pointer to the index in a[] 
    int indexArray = 0; 
    //index of a[] for max included 
    int maxToA = 0; 
    //set the first included number to the first element in a[] 
    included[indexMax] = a[indexArray]; 
    //loop until break 
    while (1) { 
     if (a[indexArray] > included[indexMax]/*digit greater than last included*/) { 
      //include the digit 
      included[indexMax+1] = a[indexArray]; 
      //increment current max pointer 
      indexMax++; 
     } 
     j = b - 1; 
     while (indexArray >= j/*pointer is at end"*/) { 
      if (j == (b - 1)) { 
       if ((indexMax+1) > max/*total is greater than current max*/) { 
        max = indexMax + 1; 
       } 
      } 
      if (a[b-1] == included[0]/*last element is in included[0], stop*/) { 
       return max; 
      } else { 
       //max included is set to zero 
       included[indexMax] = 0; 
       //max included pointer decreased 
       indexMax--; 
       //set array pointer to new max included 
       for (k=0;k<(b-1);k++) { 
        if (a[k] == included[indexMax]) { 
         indexArray = k; 
        } 
       } 
       //increment array pointer 
       indexArray++; 
       j--; 
      } 
     } 
     indexArray++; 

     printf("("); 
     for (i=0;i<b;i++) { 
      printf("%d,",included[i]); 
     } 
     printf(")"); 
    } 
} 

我收到運行時在終端中出現「分段故障(核心轉儲)」。

任何幫助都會很棒。

+4

您是否嘗試過使用'gdb'來查看發生錯誤的位置? – 2014-11-06 16:01:20

+0

我還沒有讀過你的程序,但只是看了一眼,我可以看到它使用了很多的數組。嘗試讀取數組的邊界之外可能會發生段錯誤(有時這是經典的「由一個」錯誤)。我會檢查一下,以確保你的程序沒有試圖在某個地方超出數組的最大長度。另外,看看調試。谷歌「用gdb調試seg故障」。 – nanny 2014-11-06 16:03:32

+0

使用gbp和b = 4運行時 – Tom 2014-11-06 16:06:28

回答

3

您已經聲明

int indexMax = 0; 

在這裏你使用它作爲一個數組索引

incuded[indexMax] = 0; 

你增加或減少其

indexMax++; 
... 
indexMax--; 

你檢查它的範圍,但你不t限制它,你改變你的價值與

if ((indexMax+1) > max/*total is greater than current max*/) { 
       max = indexMax + 1; 
} 

你從來不檢查indexMaxb0

int included[b]; 

所以你幾乎肯定會超過included[]界限。

一些一般性的建議。讓你的函數和變量名有意義。儘可能避免過早退出功能。儘可能避免while(1)。並且從不對數組大小(包括C「字符串」)做出假設。投入開銷看起來很困難,但有一個回報。回報不僅僅是捕捉意想不到的錯誤,它讓你考慮到你正在編寫的代碼。