PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] How to check if EOF comes first in getline() function in C?

 October 30, 2022     c, char, eof, getline, strlen     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing