Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use 4096 elements for a char array buffer?

Tags:

c

buffer

I found a program that takes in standard input

int main(int argc, char **argv) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <PATTERN>\n", argv[0]);
        return 2;
    }

    /* we're not going to worry about long lines */
    char buf[4096]; // 4kibi

    while (!feof(stdin) && !ferror(stdin)) { // when given a file through input redirection, file becomes stdin
        if (!fgets(buf, sizeof(buf), stdin)) { // puts reads sizeof(buf) characters from stdin and puts it into buf; fgets() stops reading when the newline is read
            break;
        }
        if (rgrep_matches(buf, argv[1])) {
            fputs(buf, stdout); // writes the string into stdout
            fflush(stdout);
        }
    }

    if (ferror(stdin)) {
        perror(argv[0]); // interprets error
        return 1;
    }

    return 0;
}

Why is the buf set to 4096 elements? Is it because the maximum number of characters on each line can only be 4096?

like image 392
George Newton Avatar asked Nov 14 '25 19:11

George Newton


1 Answers

The answer is in the code you pasted:

/* we're not going to worry about long lines */
char buf[4096]; // 4kibi

Lines longer than 4096 characters can occur, but the author didn't deem them worth caring about.

Note also the definition of fgets:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (\0) is stored after the last character in the buffer.

So if there is a line longer than 4095 characters (since the 4096'th is reserved for the null byte), it will be split across multiple iterations of the while loop.

like image 55
rampion Avatar answered Nov 17 '25 14:11

rampion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!