Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fread example from C++ Reference

Tags:

c

fread

I often use the website www.cplusplus.com as a reference when writing C code.

I was reading the example cited on the page for fread and had a question.

As an example they post:

/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>

int main () {
  FILE * pFile;
  long lSize;
  char * buffer;
  size_t result;

  pFile = fopen ( "myfile.bin" , "rb" );
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

  // obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  buffer = (char*) malloc (sizeof(char)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,pFile);
  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

  /* the whole file is now loaded in the memory buffer. */

  // terminate
  fclose (pFile);
  free (buffer);
  return 0;
}

It seems to me that that if result != lSize, then free(buffer) will never get called. Would this be a memory leak in this example?

I have always thought the examples on their site are of a very high quality. Perhaps I am not understanding correctly?

like image 736
Tim Avatar asked Jul 05 '26 06:07

Tim


2 Answers

It wouldn't be a memory leak in this example, because terminating the program (by calling exit()) frees all memory associated with it.

However, it would be a memory leak if you used this piece of code as a subroutine and called something like return 1; in place of exit().

like image 119
jpalecek Avatar answered Jul 07 '26 20:07

jpalecek


Technically, yes it is a memory leak. But any memory allocated by a process is automatically freed when that process terminates, so in this example the calls to free (and fclose) are not really required.

In a more complex program, this would probably be a real problem. The missing free would create a memory leak and the missing fclose would cause a resource leak.

like image 38
Ferruccio Avatar answered Jul 07 '26 19:07

Ferruccio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!