簡體   English   中英

獲取C ++分段錯誤

[英]Getting a C++ segmentation fault

我在linux服務器中,當我嘗試執行該程序時,它返回了分段錯誤。 當我使用gdb嘗試找出原因時,它會返回。

Starting program: /home/cups/k

Program received signal SIGSEGV, Segmentation fault.
0x0000000000401128 in search(int) ()
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.192.el6.x86_64 libgcc-4.4.7-17.el6.x86_64 libstdc++-4.4.7-17.el6.x86_64

我不能完全解釋這一點。 在我的程序中,我有一個名為“ search()”的函數,但我看不到任何會導致段錯誤的東西。 這是函數def:

int search (int bit_type) {                                               // SEARCH FOR A CONSEC NUMBER (of type BIT_TYPE) TO SEE IF ALREADY ENCOUNTERED

    for (int i = 1; i <= MAX[bit_type]; i++) {               //GO THRU ALL ENCOUNTERED CONSEC NUMBERS SO FAR (for type BIT_TYPE)
        if (consec == r[bit_type][i])                           // IF: FOUND
        return i;                                                                       //                      -----> RETURN INDEX OF RECORDED CONSEC_NUM
    }
    // IF: NOT FOUND
    r[bit_type][++MAX[bit_type]] = consec;                          //                      -----> INCREMENT MAX[bit_type]  &  RECORD NEW CONSEC_NUM -------> ARRAY[MAX]
    n[bit_type][MAX[bit_type]] = 1;
    return (MAX[bit_prev]);                                                          //                      -----> RETURN THE NEWLY FILLED INDEX 
}

全局功能:

int MAX[2];
int r[2][200];
int n[2][200];

因為您沒有程序的其余部分,所以注釋對您來說毫無用處。但是您可以忽略它們。

但是你們看到我想念的東西嗎?

此處的代碼鏈接,這只是一個錯誤:

 int *tmp = new int[MAX[0]];
 for (int y = 0; y <= MAX[0]; y++) {
     tmp[y] = 1;
}

您在上一次迭代中越界。 您為數組分配了MAX[0]項目,在上一次迭代中,您正在訪問tmp[MAX[0]]

該循環應為:

 int *tmp = new int[MAX[0]];
 for (int y = 0; y < MAX[0]; y++) {
     tmp[y] = 1;
}

或更好:

 #include <algorithm>
    //...
    std::fill(tmp, tmp + MAX[0], 1);  // no loop needed

或使用new[]跳過動態分配,並使用std::vector

  #include <vector>
  //...
  std::vector<int> tmp(MAX[0], 1);

通常,您有多個執行此操作的循環:

for (int i = 1; i <= number_of_items_in_array; ++i )

然后使用array[i]訪問數組。 for循環條件中的<=令人懷疑,因為它會在上一次迭代時嘗試使用越界索引訪問數組。

另一個例子是這樣的:

long sum(int arr_r[], int arr_n[], int limit)
{
    long tot = 0;
    for (int i = 1; i <= limit; i++)
    {
        tot += (arr_r[i])*(arr_n[i]);
    }
    return tot;
}

在這里, limit是數組中元素的數量,您在最后一次迭代中訪問arr_r[i] ,從而導致未定義的行為。

數組從0到n - 1索引,其中n是元素總數。 在嘗試偽造基於1的數組時,幾乎總是會在代碼庫內部的某些地方導致這些類型的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM