0

Here's my piece of code(the purpose is to read line and make a structure out of it):

typedef struct{
   size_t length;
   char *letters;
}line;
static line ReadLine(){
    char *buffor = NULL;
    size_t length = 0;
    int nRead = 0;
    nRead = getline(&buffor, &length, stdin);
    return nRead == -1 ? (line) {.length = 0, .letters = NULL} : (line) {.length = nRead, .letters = buffor};
}

Later on in my main function I free the buffor that was allocated by getline function:

void ReadFile(){
line l = ReadLine();
printLine(l);
free(l.letters);
}

And yet i get that there is some memory(using valgrind): Leak_StillReachable by malloc in which the function getline is.

Yashiru99
  • 43
  • 1
  • 7

2 Answers2

1

Okay, so after some time I figured out that if getline() fails to allocate memory it still allocates the buffer, so f.e if nRead == -1(which indicates an error in getline) we have to free the buffer. Otherwise I return

(line) {.length = 0, .letters = NULL}

And I lose a pointer to buffer, which was despite an error allocated.

Yashiru99
  • 43
  • 1
  • 7
0

Memory for getline() should be allocated using malloc(), try to change line (char* buffor = NULL) with line (char* buffor = (char*)malloc(count * sizeof(char)); ) where count is the max length for input string.

otokkk
  • 21
  • 3
  • 2
    getline() calls realloc itself if there is no enough space allocated, that may cause the issue you mentioned. – otokkk May 17 '21 at 13:05
  • _"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.)"_ (man getline) – Zilog80 May 17 '21 at 13:06
  • In case of `realloc`, the preceding allocated space is freed by `realloc` : _"f the new size of the memory object would require movement of the object, the space for the previous instantiation of the object is freed"_ – Zilog80 May 17 '21 at 13:13
  • There is no maximum input length specified. – Yashiru99 May 17 '21 at 13:16