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 settinglineptr
andn
to NULL). Otherwise it will reuse the buffer thatlineptr
points to, and for that it needs to ensure the buffer is large enough. If the size of the buffer is not known, thenrealloc()
would have to be called on every invocation to ensure it's big enough.getline()
will also resize the buffer more than1
byte at a time (to make it amortized linear time instead of n^2), for example, I read3
bytes (size) but it allocated120
bytes (capacity).
do you know?
how many words do you know