for some reason I get a segmation fail(core dump) but only on the second run in the loop. some background ptr is declared as char* in main() and initialized as NULL. Attaching screenshot of the code and prints
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;
}
CodePudding user response:
**(str i)=c;
it needs to be *(*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);
}