Length of line in getline() function – c

c

I have a question regarding the function getline():

getline(&line, &len, file_in);

where file_in is:

FILE *file_in;

char *line = NULL;

size_t len;

Every time when I read any line the allocated memory (len variable) is 120

I suppose that it is constant, because it is a default line size in a file.

1) But why 120?

2) Can this default size be changed anywhere?

3) Is there any C function that counts only written chars?

Best Answer

  1. Using 120 as an initial allocation is a sensible choice made by those who wrote the library; it is longer than most lines, so there's a decent chance it will only have to do one memory allocation. (FWIW: I wrote an implementation of getline() and getdelim() to use on machines without a version in the standard library. It used 256 as the minimum allocation (rather than 120) — except when compiled for testing, when it used 8 as the starting point to make sure the reallocation code gets more exercise. The allocated size doubles when there isn't enough room. It was a similar thought process to what the library designers did in the library you use; get the memory allocation big enough first time around that the code mostly won't need to reallocate.)
  2. You can find the code in the library, change the default, and rebuild the library. OTOH, that's hard work.
  3. There's a function called getline() that tells you how many chars were in the line it just read via its return value. Note that it returns -1 (not EOF) on error. Although it seldom happens, it is theoretically possible for EOF to be a negative value other than -1.

You can also rig the system to use shorter lines (until you read a long line) by:

FILE *file_in;
size_t len = 16;
char *line = malloc(len);

And (for the ultimate in sleazeball programming) you don't even have to error check the allocation since char *line = NULL; is also a valid input to getline():

ssize_t nbytes;

while ((nbytes = getline(&line, &len, file_in)) > 0)
    ...process a line of nbytes including newline...
Related Topic