Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22250

A function to read new line in c from a given stream

$
0
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);    /*do stuff hier*/    free(a);    return 0;}int getLine(char** string, FILE* stream){    if (strlen(*string)>0)    {           free(*string);        *string = (char *) malloc(sizeof(char));    }    char* tmp;    unsigned laenge=0u;    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


Viewing all articles
Browse latest Browse all 22250

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>