user189728
user189728

Reputation: 288

C getline continuing to take input after newline

I am trying to essentially take in a line of text from the user, and reverse it.

#define LENGTH 0xFF

char *buffer = malloc(LENGTH), *output = malloc(LENGTH);
unsigned char length_read, count = 0;
length_read = getline(&buffer, 0, stdin);

while (length_read >= 0)
  output[count++] = buffer[length_read--];

In theory, the value of output should be the reverse of buffer. But when I run my program, getline seemingly doesn't stop reading input from the keyboard and the program doesn't advance. I'm using gcc with -std=c11. Out of curiosity, I put two different calls to printf on either side of the line calling getline, and both printed their outputs. I'm not really sure I'm what I'm doing wrong or misinterpreting.

Upvotes: 0

Views: 129

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753475

In your code, you have:

char *buffer = malloc(LENGTH);
unsigned char length_read;
length_read = getline(&buffer, 0, stdin);

What makes you think you can pass a null pointer for the length? The POSIX specification for getline() certainly does not allow it — it requires that the function can write to *n. I see no relief in the Linux man pages for getline(3) either. I think you're using undefined behaviour; I'm surprised you aren't simply crashing.

Additionally, if both your printf() statements print, then getline() itself isn't stuck.

Using unsigned char for the return value from getline() is dicing with death — it returns a ssize_t which is usually at least 4 bytes and often 8 bytes long. You may be misunderstanding what it returns, especially if it encounters EOF and returns -1 (and -1 is its return value when it encounters EOF, not EOF, though the two are usually the same).

A more typical use would be:

char *buffer = 0;
size_t buflen = 0;

ssize_t length_read = getline(&buffer, &buflen, stdin);

Don't forget to free buffer even if the input fails; memory may have been allocated even if it immediately gets EOF.

Upvotes: 3

Related Questions