cpointersgetlinesize-tcstdio

C getline() function: return value vs second argument


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?


Solution

  • 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: