user1234567 user1234567 - 3 months ago 10
C Question

How should I store the first line that got from getline() in c?

int main(){
char *input = NULL;
char *first = NULL;
size_t len = 100;
int count = 0;
while(getline(&input, &len, stdin)!= EOF){
if(count == 0){
first = input;
printf("------>%s, count = %d\n", first, count);//test printer
printf("%d, %s, %s\n", count, input, first);//test printer

return 0;

I was trying to seperate two parts --the first line I input and rest of string after the first line...but I don't know why I can't store first line seperately successfully.

In order to stop assignning input to first(first line input), I used count to determine where should I stop which means if count is zero which means my input is first line. And then in the while loop, after the second line you input, you will print second line, first line...I set test printer on else statement, I found the first changed when I input the second line. Which means when jump to else statement, first is not printing what I want(actual first line) but the same line as input.

I am so confusing about this. Why the value changed? How should I store the first line value at a separately char array?


It's because you make first point to the same memory as input. Both variables are pointing to the same memory after the assignment first = input.

You need to duplicate the string instead, using e.g. strdup:

first = strdup(input);

Also note that you are using the getline function wrong. From the manual page:

If *lineptr is set to NULL and *n is set 0 before the call, then getline() will allocate a buffer for storing the line

For the getline function to allocate memory you need to setlen to zero too. Or allocate memory yourself. If *n is not zero the above text implies that the getline call does not allocate memory, but uses the pointer *lineptr as it was valid and pointing to allocated memory of at least *n bytes. You have a null-pointer, which will lead to *undefined behavior as getline uses that pointer and writes to the memory it points to.

And remember that if you ask getline to allocate memory for you, and you use strdup, then you need to free that memory.

Lastly, getline can modify the length so you need to reset it before every call.