I'd like to read a line from stdin, excluding the newline character. I've written the function:

/* read in a line from stdin, NULL on failure
 * does not include trailing newline
readStdinLine() {
        char* buffer;
        size_t bufsize = 32;
        size_t characters;

        buffer = (char *) malloc(bufsize * sizeof(char));
        if (buffer == NULL)
                return NULL;

        characters = getline(&buffer, &bufsize, stdin);
        buffer[--characters] = '\0';

        char* text = (char *) malloc(characters);
        for (int i = 0; i < characters + 1; i++) {
                text[i] = buffer[i];


        return text;

This seems inneficient, I'm essentially reading in the line twice, once in getline and once to remove the trailing newline. That doesn't seem like the most memory-efficient algorithm, and I would like to remove the newline without copying, if that is at all possible.

I'm very new to C (have used C++, Java, etc, but never a systems language without objects) so I would appreciate learning all the code style things I've done wrong as well. Thanks!

  • 1
    \$\begingroup\$ I don't see the need for this. getline() does all this automatically. If you want a version that removed the newline character then you simply remove it (if it exists (Note last line in a file may not have a new line)). \$\endgroup\$ Nov 1 '20 at 18:12
  • 1
    \$\begingroup\$ Do note that getline isn't a standard C function and you should probably tag the question accordingly. \$\endgroup\$ Nov 2 '20 at 6:43

This function can be written like this:

char* readStdinLine()
        char*  buffer  = NULL;
        size_t bufsize = 0;
        ssize_t characters = getline(&buffer, &bufsize, stdin);
        if (characters == -1) {
            buffer = NULL;
        else if (buffer[characters-1] == '\n') {
            buffer[characters-1] = '\0';
        return buffer;

The getline() function does everything you need. You simply need to check for errors and remove the new line character)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.