Home > Blockchain >  C getline() function: return value vs second argument
C getline() function: return value vs second argument

Time:08-19

Do the return value (type ssize_t) of the C getline function and the second argument *n (type size_t) contain the same information, after invocation? Empirically, it seems that *n equals (size_t)pow(2, ceil(log2(<return value> 1))). Is this relation true in general? Can someone explain its (in)validity, conceptually?

CodePudding user response:

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

Do the return value (type ssize_t) of the C getline function and the second argument *n (type size_t) contain the same information, after invocation?

No. The return value is the count of characters read, not including the appended null character. *n is the size of the current allocation of *lineptr. The return value is signed and is -1 when an (allocation) error/end-of-file occurs. *n is an unsigned type.

It is expected that the return value is always less than *n.

it seems that *n equals (size_t)pow(2, ceil(log2( 1))). Is this relation true in general?

No, *n may or may not be a power of 2.

getline() is not part of the C standard library and implementations differ on allocation details.


*n equals (size_t)pow(2, ceil(log2(<return value> 1))) is invalid when:

  • return value == -1

  • getline() does not re-allocate and the passed in size was not a power-of-2.

  • getline() reallocates and is not using a power-of-2 scheme.

  • Pedantic: Very large return value round down in the conversion to double in the log2(_return value_ 1) step.

  • ...

  • Related