[英]segmation fail on 2nd run of the loop
出于某种原因,我得到一个分段失败(核心转储),但仅在循环中的第二次运行时。 一些背景 ptr 在 main() 中声明为 char* 并初始化为 NULL。 附上代码和打印的屏幕截图
char* get_command(char **str) {
char c;
int i,add=0;
printf("\tget command\n");
for(i=0; (c=getchar())!= '\n';i++) {
if(i==TOTAL_CHAR*add){
*str = (char*)realloc(*str,sizeof(char)*TOTAL_CHAR*
(++add));
printf("\tmemory alocate succede\n");
if (*str==NULL) {/*warning if realloc has failed*/
fprintf(stderr,"ERROR:: realloc fail");
exit(0);
}
}
**(str+i)=c;
printf("\tchar should be: %c, actual: %c\n",c,**(str+i));
}
return *str;
}
**(str+i)=c;
它必须是*(*str+i)=c;
char* get_command(char **str)
{
char c;
int i,add=0;
printf("\tget command\n");
for(i=0; (c=getchar())!= '\n';i++)
{
*str = (char*)realloc(*str, i + 2);
if (*str==NULL)
{/*warning if realloc has failed*/
fprintf(stderr,"ERROR:: realloc fail\n");
free(*str);
exit(0);
}
*(*str+i)=c;
printf("\tchar should be: %c, actual: %c\n",c,*(*str+i));
}
*(*str + i) = 0;
return *str;
}
int main(void)
{
char *s = NULL;
get_command(&s);
printf("string: \"%s\"\n", s);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.