2017-08-24 95 views
0

這裏是我的代碼分段故障循環

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main() 
{ 
    char str[] ="a,b,c,d,e"; 

    struct stri { 
      int i; 
      char *data; 
    }; 
    struct stri **pstri = NULL; 
    char *pch; 
    pch = strtok (str,","); 
    int i = 0; 
    while (pch != NULL) 
    { 
    printf("before: %s\n", pch); 
    pstri = realloc(pstri, (i + 1) * sizeof(struct stri*)); 
    struct stri *s = malloc(sizeof(struct stri)); 
    s->i = i; 
    s->data = strdup(pch); 
    pstri[i] = s; 
    i++; 
    pch = strtok (NULL, ","); 
    } 
    //update 
    // should I realloc here too? 
    pstri[i] = NULL; 
    //update 


    int j = i; 
    for(i = 0; i<j; i++) { 
    printf("after: %d=>%s\n", pstri[i]->i, pstri[i]->data); 
    } 

    struct stri *k = NULL; 
    while(k = *pstri++) { 
    printf("after2: %d=>%s\n", k->i, k->data); 
    } 

    return 0; 
} 

輸出

before: a 
before: b 
before: c 
before: d 
before: e 
after: 0=>a 
after: 1=>b 
after: 2=>c 
after: 3=>d 
after: 4=>e 
after2: 0=>a 
after2: 1=>b 
after2: 2=>c 
after2: 3=>d 
after2: 4=>e 
Segmentation fault 
+2

您需要爲'NULL'指針保留額外的內容並將其設置爲最後一個元素。 (也是'* pstri ++':如果'pstri'直接被改變,它必須在'free'之前被返回) – BLUEPIXY

+0

分段錯誤可能由以下原因之一引起:(1)解除引用空指針(當試圖做*開(2)如果'pstri + 5'處的數據不爲0,則數據在'pstri + 5'處打印後''(pstri + 5)',因爲'pstri + 5'處的數據可以全部爲0。在'k = *(pstri + 5)'時可能爲零,這會由於在嘗試執行k-> i或k-> data時取消引用空指針而導致seg錯誤。如果'k = *(pstri + 5)'處的數據不爲零,但是當程序正在尋找'k-> data'的空終止符時,'k-> data'可能會將程序放在允許的內存區域之外。 –

+0

爲避免出現這種情況,您可能需要:將'pstri + 5設置爲NULL'並修改爲'while((k = * pstri ++)!= NULL)' –

回答

0

While循環退出時pch = strtok (NULL, ",")使得PCH NULL但我們還沒有在i = 5爲pstri設置爲NULL。如果您設置j = 6而不是j = i,則可能發生相同的分段錯誤,因爲i正在保護此after:循環。

+0

你好,我更新了代碼,是否正確? – Sato