I have written a code that allocated a buffer that get assigned the file's contents. Running the code through valgrind gives me this
total heap usage: 9 allocs, 7 frees, 10,905 bytes allocated
If I am not mistaken the code allocates only 3 times, and I am deal locating when needed.
void read_from_file (const char* filename, size_t length, char* buffer)
{
/* put your code here */
FILE* fOpen;
buffer = (char*)malloc(length+1);
fOpen = fopen(filename, "r");
if(!buffer) // --- Failed to allocate
printf("Failed to allocate...\n");
else if(!fOpen){ // --- Failed to open file
free(buffer);
fprintf(stdout, "Failed to read %s\n", filename);
buffer = NULL;
}
else if(fgets(buffer, length+1, fOpen)!=NULL){ // Buffer has been copied
fprintf(stdout, "buff is: %s\n", buffer);
free(buffer);
buffer = NULL;
}
else{ // --- Failed to copy correctly
fprintf(stdout, "Failed to copy %s file...\n", filename);
free(buffer);
buffer = NULL;
}
}
void main (int argc, char **argv)
{
char* buff = NULL;
read_from_file("test1.txt",10,buff);
read_from_file("test2.txt",10,buff);
read_from_file("test3.txt",10,buff);
}