What's purpose of __linecapp in getline, when it'll auto resize?

It's all about second parameter of getline in stdio.h,

I'll name it 'n' or '__linecapp' below.

According to the document:

If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary.

It'll automatically update line capacity, then why should we input __linecapp?

P.S Someone ask before, but discussion didn't explain when we need it, or how to make it useful.

1 answer

  • answered 2022-05-07 06:37 Allan Wind

    Heap allocation is a relatively expensive operation so you want to minimize those to be efficient.

    getline() will only allocate a new buffer if requested (by setting lineptr and n to NULL). Otherwise it will reuse the buffer that lineptr points to, and for that it needs to ensure the buffer is large enough. If the size of the buffer is not known, then realloc() would have to be called on every invocation to ensure it's big enough. getline() will also resize the buffer more than 1 byte at a time (to make it amortized linear time instead of n^2), for example, I read 3 bytes (size) but it allocated 120 bytes (capacity).

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum