Home > database >  C: How do I properly free the memory when lineptr == NULL in getline
C: How do I properly free the memory when lineptr == NULL in getline

Time:12-16

From the man page: https://linux.die.net/man/3/getline

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

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.)

Since is a school project I CAN NOT USE MALLOC by teacher instructions, I don't care about the contents of the line (I just want to skip it easily). How can I free the memory? in which buffer it is allocated?

Note: Since it is a more theoretical question I do not add any code

CodePudding user response:

Here's an example usage:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    char *line = NULL;
    size_t line_size = 0;
    
    while (1) {
        ssize_t line_char_count = getline(&line, &line_size, stdin);
        
        if (line_char_count == -1) break;
        
        // Use your line string, e.g. printing it:
        printf("Echo: %s", line);
    }
    
    free(line); 
}

What you'll notice is that the string line is NULL to start. As the documentation explains, the first invocation of getline will make it allocate a buffer for you (as if it called malloc internally). Subsequent calls to getline in the loop will reuse the same buffer.

Once you send end-of-input with ctrl-d, the loop will exit, and free will be called to free the line.

CodePudding user response:

I don't care about the contents of the line (I just want to skip it easily).

Instead of getline(), code could use a simply loop. No allocation worries.

int ch;
while ((ch = fgetc(stream)) != '\n' && ch != EOF) {
  ;
}
  • Related