size_t vs long

I understand that size_t is used to:

(1) optimize performance; and
(2) improve portability

when storing integer values that represent bytes, but the following code
from cplusplus.com appears to be inconsistent:

1
2
 long lSize;
  size_t result;


1
2
result = fread (buffer,1,lSize,pFile);
  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}


If result is going to be compared to lSize, why not make them both size_t
variables? Why is lSize long and result size_t?

CONTEXT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* fread example: read an entire 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;
}
I think lSize is of type long because the return value of ftell is long, and result is size_t because fread returns size_t.
This code is written provided that sizeof( size_t ) is equal to sizeof( long ). But this assumption is valid only for 32-bit systems. So this code is depended on the system where it is used. Of course it is a bad code but it is not easy to write system-independent code where functions fread and ftell are used simultaneously. I can point another drawback in the statement

buffer = (char*) malloc (sizeof(char)*lSize);

Again if sizeof( size_t ) is less than long then there is a truncation of the expression sizeof(char)*lSize.
How would size_t be less than long? Isn't size_t used precisely because it
is guaranteed to be big enough to contain the size of the biggest object
the system can handle -- i.e., larger than long, by definition.
size_t is big enough to store the size of any object

size_t sizeOfLong = sizeof(long);

but that doesn't mean size_t has the same size as the biggest object. That would be a waste of memory.
Last edited on
Topic archived. No new replies allowed.