当我将 0 作为 getline 的第二个参数传递时会发生什么?

What happens when I pass 0 as the second parameter of getline?

cplusplus.com表示getline函数的第二个参数是

Maximum number of characters to write to s

不过,我见过这样的代码:

size_t linecap = 0;
ssize_t linelen;
linelen = getline(&line, &linecap, fp);

这不会从源中读取 0 个字节吗?还是有其他事情发生?

不,这不正确。来自man page,(强调我的

If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program. (In this case, the value in *n is ignored.)

Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary.

In either case, on a successful call, *lineptr and *n will be updated to reflect the buffer address and allocated size respectively.

所以,第二个参数指向的内存中存储的初始值对实际扫描没有影响。值被扫描并填充到缓冲区后,

  • 函数 return 值将告诉您扫描输入的大小(以字节为单位)。
  • *n 的值将告诉您分配用于存储输入的缓冲区的大小(通常大于扫描输入的大小)。

getline 的想法是重新分配尽可能少,因为对 malloc 的调用往往很昂贵。因此,如果您重复使用 getline 来读取文件中的行,重复使用相同的缓冲区和长度,缓冲区最终会增长到文件中最长行的大小,并且不需要重新分配最长行之后的行。

但要使其正常工作,必须遵循某些合同 - 也就是说,如果 *lineptrnon-NULL,那么它

  • 必须是由 malloc
  • 编辑的指针 return
  • 分配大小必须至少为 *n 字节

推论:在 *n 中传递 0 在这两种情况下没问题:

  • 如果 *lineptrNULL
  • *lineptr任何 活指针 return 由 malloc 编辑(作为任何指针 return 由 malloc 将有 0 个字节 space).

在这两种情况下,*n 将更新为行的长度,并且 realloc(*lineptr, new_line_length_with_terminator) 的 return 值(如果成功)将分配给 *lineptr.

当然