双指针循环中的分段错误

时间:2017-08-24 01:39:13

标签: c

这是我的代码

#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

1 个答案:

答案 0 :(得分:0)

pch = strtok (NULL, ",")使pch为NULL时循环退出,但我们无法在i = 5为pstri设置NULL。如果您设置j = 6而不是j = i,则会发生同样的细分错误,因为i正在保护此after:循环。

相关问题