1

I have the following program :

/* a.c */ 
#include <stdio.h>

int   
main(int argc, char* argv[]){     

size_t size=0;    
char* lineptr;      

    while(getline(&lineptr, &size, stdin)){           
        fprintf(stderr, "line = %s\n", lineptr);      
        if(lineptr){      
            free(lineptr);     
            lineptr = NULL;     
        }      
    }      

return 0;      
}      

I redirected the output of shell command "ls" to this program using the
following line :

ls | ./a.out

Expected output :
program should print the name of all files in the current directory
and terminate.

Actual output :
The program prints the name of all the files but does not terminate,
instead it loops infinitely and prints the last entry infinitely.

Thanks

3
  • 2
    Did you read the manual for getline? Commented Feb 16, 2015 at 18:35
  • I was ignoring the return value of getline. at the end it returns -1 which happens to be a true value, thus the infinite loop. Commented Feb 16, 2015 at 18:36
  • Since you aren't using the arguments, you'd do better to be explicit about that and write int main(void). Commented Feb 16, 2015 at 18:43

1 Answer 1

4

GNU's getline function returns -1 upon end-of-file (or error). Use

while(-1 != getline(&lineptr, &size, stdin))

...and set lineptr to NULL before the first call to getline.

Also, you don't have to free the pointer in every iteration of the loop; you can reuse the previous pointer and free once at the end:

size_t size = 0;
char* lineptr = NULL;

while(-1 != getline(&lineptr, &size, stdin)){
  fprintf(stderr, "line = %s", lineptr);
}

free(lineptr);

getline will use realloc internally as needed. Note that you have to make sure that lineptr and size are not changed between calls to getline for this to work (although you may change the string to which lineptr points).

Sign up to request clarification or add additional context in comments.

2 Comments

I read the manual, it says if lineptr is NULL, then the value of size is ignored, so i made lineptr to be NULL after every iteration
That works, but it is inefficient. There is no need to do a heap allocation every iteration, only when the allocated space is too small and has to be enlarged. getline handles this internally, so there's no need not to take advantage of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.