Issue
I have this code:
int main(void){
printf("Type something:\n");
while(1){
char * array = NULL;
size_t size = 0;
getline(&array, &size, stdin);
if( (strlen(array) == 0) && feof(stdin) ){
free(array);
return 0;
};
/* do something else */
free(array);
}
return 0;
}
I want to end my program, when the first thing comes from input is EOF, but valgrind shows Conditional jump or move depends on uninitialised value(s)
. I know the problem must be strlen(array)
, but do not know, how to do it a different way. I can do:
if(feof(stdin)){
free(array);
return 0;
}
but, if someone type a string and then end it with EOF, my program would stop too and I don't want that (because I need to do something else with that string). Any suggestion please? I am a beginner at C language.
Solution
As @wildplasser suggested, use the following code.
int main(void){
printf("Type something:\n");
while(1){
char * array = NULL;
size_t size = 0;
ssize_t read = getline(&array, &size, stdin);
if((read < 0 || (strlen(array) == 0)) && feof(stdin) ){
free(array);
return 0;
};
/* do something else */
free(array);
}
return 0;
}
Answered By - Abhijit Mondal Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.