分段在循环的第 2 运行 处失败

segmation fail on 2nd run of the loop

出于某种原因,我遇到了分段失败(核心转储),但仅在循环中的第二个 运行 上。某些背景指针在 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;
}

enter image description here

**(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);
}

https://godbolt.org/z/T4PMTjn3s