这是我的代码
#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
答案 0 :(得分:0)
当pch = strtok (NULL, ",")
使pch为NULL时循环退出,但我们无法在i = 5
为pstri设置NULL。如果您设置j = 6
而不是j = i
,则会发生同样的细分错误,因为i
正在保护此after:
循环。