0

I'm experimenting with a c function that reads a new line from a given FILE* let's assume the pointer beforehand has already been malloced.

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



int getLine(char** string, FILE* stream);
int main(){
    char* a = (char*) malloc(10);
    getLine(&a, stdin);
    printf("%s\n", a);
    free(a);
    return 0;
}

int getLine(char** string, FILE* stream){
    char* tmp;
    unsigned laenge=0u;
    if (strlen(*string)>0)
    {   
        free(*string);
        *string = (char *) malloc(sizeof(char));
    }
    do
    {
        tmp=(char *)realloc(*string,++laenge);  
        if(tmp==NULL)
        {
            printf("Allokation fehlgeschlagen\n");
            free(*string);
        }
        *string=tmp;
        (*string)[laenge-1]=fgetc(stream);
        if (feof(stream))
        {   
            (*string)[laenge-1]='\0';
            return EOF;
        }
    }
    while((*string)[laenge-1]!='\n');
    (*string)[laenge-1]='\0';
    return laenge;

}

I need this to be right before I use it in my assignment and I only have one shot at this. <(^.^')v

Your opinion is of great value to me.

  1. Could any memory leak happen in this case?
  2. Is it a good practice to use a function like this?
  3. Am I missing anything?

If that may help, I have to stick to the C89 standards and I'm using gcc -ansi -pedantic -Wall to compile my code

  • 1
    The code doesn't compile in C89 mode because the `if` statement precedes the variable declaration. – Roland Illig Jun 05 '20 at 06:06
  • `while((*string)[laenge-1]!='\n');` is an endless loop. Really, use [`getline`](https://linux.die.net/man/3/getline). Your function has many bugs. Your handling of `realloc` is wrong - after you `free(*string)` you still use `*string = tmp` and dereference it - it's NULL then! – KamilCuk Jun 05 '20 at 07:13
  • Do not cast the return from `malloc`. https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Jens Jun 05 '20 at 09:20

1 Answers1

0

I would recommend using fgets instead of trying to write your own function for reading lines from a FILE pointer, as fgets reads a maximum of n characters into a buffer string and stops reading upon encountering a newline.

However, if, for your project, it's required that you read a full line of arbitrary length from a FILE pointer, I would suggest using realloc to grow the buffer and reading with fgets to the additional space so allocated until the buffer is not full.

  • So that would mean I should read for instance 10 chars with `fgets` instead of `fgetc` and as long as it doesn't return `Null` increase the size with `realloc` by 10? I would have used scanf and a static array, but my Project require me to read strings from a .txt file and from stdin with arbitrary length. :/ \*cries in pointers\* – Mouaz Tabboush Jun 05 '20 at 20:22
  • @MouazTabboush yes, pretty much. – Joseph Pilliner Jun 09 '20 at 09:16