fread example from C++ Reference

18,771

Solution 1

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().

Solution 2

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.

Share:
18,771
Tim
Author by

Tim

B.A. Comp Sci

Updated on October 19, 2022

Comments

  • Tim
    Tim over 1 year

    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?