取下面的代码,在a.c
中:
struct header {
char **name;
};
int main(void)
{
int i=0;
char **p;
struct header h;
char tmp[10];
memset(&h, 0, sizeof(h));
for(i=1;i<10;i++){
sprintf(tmp, "name%d", i);
p = realloc(h.name, sizeof(char*)*i);
printf("h->name=%p, p=%p\n", h.name, p);
h.name = p;
h.name[i-1] = malloc(100);
strncpy(h.name+i-1, tmp, strlen(tmp));
printf("h->name=%s\n", h.name+i-1);
}
return 0;
}
在我 gcc a.c
和 ./a.out
之后,发生以下错误:
段错误
我对此一无所知,到底发生了什么?
编辑1:
找到问题了!
strncpy(h.name+i-1, tmp, strlen(tmp))
应该 strncpy(h.name[i - 1], tmp, strlen(tmp) + 1)
并且这个问题可以通过 gcc warnings:/usr/include/string.h:131:14: note: expected 'char * __restrict__' but argument is of type 'char **'
找到,真傻!感谢大家!
最佳答案
strncpy(h.name+i-1, tmp, strlen(tmp));
不会以 null 终止目标字符串。可能是下一个 printf()
试图打印它时崩溃了。
关于c - 重新分配 : Segmentation fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16975187/