You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

The size_t type is the unsigned integer type of the result of the sizeof operator. The underlying representation of variables of type size_t are guaranteed to be of sufficient precision to represent the size of an object. The limit of size_t is specified by the SIZE_MAX macro.

Any variable which is used to represent the size of an object including, but not limited to, integer values used as sizes, indices, loop counters, and lengths should be declared as size_t.

Non-compliant Code Example 1

In the following example, the dynamically allocated buffer referenced by p will overflow for values of n > INT_MAX.

char *copy(size_t n, char *str) {
  int i;
  char *p = malloc(n);
  for ( i = 0; i < n; ++i ) {
    p[i] = *str++;
  }
  return p;
}

char *p = copy(20, "hi there");

Compliant Code Example 1

Declaring i to be of type size_teliminates the possible integer overflow condition.

char *copy(size_t n, char *str) {
  size_t i;
  char *p = malloc(n);
  for ( i = 0; i < n; ++i ) {
    p[i] = *str++;
  }
  return p;
}

char *p = copy(20, "hi there");

References

  • No labels