#include "txtfile.h" void strcat_mem(char **dest, char * src) { char * buf; if (*dest != NULL) { buf = (char*)calloc(strlen(*dest) + strlen(src), sizeof(char)); strcpy(buf, *dest); strcat(buf, src); free(*dest); } else { buf = (char*)calloc(strlen(src), sizeof(char)); strcat(buf, src); } *dest = buf; } char *fstrread(FILE *f) { char *line = NULL; char *buf = calloc(BUF_LEN, sizeof(char)); while (fgets(buf, BUF_LEN, f) != NULL) if (buf[strlen(buf) - 1] == '\n') { strcat_mem(&line, buf); break; } else strcat_mem(&line, buf); free(buf); strtok(line, "\n"); return line; } 

Main program code

 #include <stdio.h> #include <string.h> #include <stdlib.h> #include "errcode.h" #include "txtfile.h" int main(int argc, char* argv[]) { FILE *f =fopen("in.txt", "rt"); printf("%s\n", fstrread(f)); fclose(f); return ERR_OK; } 

    2 answers 2

    The first mistake you have here:

     FILE *f =fopen("in.txt", "rt"); 

    You do not check the error when opening the file.

    The second is here:

     buf = (char*)calloc(strlen(*dest) + strlen(src), sizeof(char)); /* ... */ buf = (char*)calloc(strlen(src), sizeof(char)); 

    In memory, in both cases, you are allocated 1 byte less than you need (you forgot about the trailing 0 in the C-lines). The behavior of the program in this case is not defined. In some situations, the fact of writing beyond the allocated buffer may not affect anything, while in others it may format the hard drive ...

    And the third flaw here:

     printf("%s\n", fstrread(f)); 

    A pointer to the memory that is allocated in fstrread() is not saved anywhere and the memory is not freed. In this case, it is not scary (the memory will still be released at the end of the program), but in general this is a bad habit.

      Well, for example...

       buf = (char*)calloc(strlen(src), sizeof(char)); strcat(buf, src); 

      And who will select the place for the zero character? ... You allocate strlen(src) bytes, and you copy strlen(src)+1 ...