2017-08-24 92 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