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.
- Could any memory leak happen in this case?
- Is it a good practice to use a function like this?
- 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