简体   繁体   English

双指针循环中的分段错误

[英]Segmentation fault in double pointer looping

Here is my code 这是我的代码

#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;
}

output is 输出是

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

While loop exit when pch = strtok (NULL, ",") makes pch NULL but we haven't set NULL at i = 5 for pstri. pch = strtok (NULL, ",")使pch为NULL时,虽然退出循环pch = strtok (NULL, ",")但我们尚未将pstri的i = 5设置为NULL。 This same segmentation fault can happen if you set j = 6 instead of j = i because i is protecting this after: loop. 如果您设置j = 6而不是j = i ,则可能会发生相同的分段错误,因为i after:对此after:保护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM