size_t type --type representing size

The size_t type is a type that represents the size. An unsigned integer of 16 bits or more is a necessary condition in the specifications.

Assume that it is defined as an unsigned 32-bit integer in a processing system that handles a 32-bit address space, and as an unsigned 64-bit integer in a processing system that handles a 64-bit address space.

// Type representing size
size_t

What is the size intended by the size_t type in the first place?

What I don't understand when I encounter the size_t type is the size, but what is the size that the size_t type intends to do in the first place?

The intent is probably an abstraction of address space size. If it is a 32bit CPU, the memory space that can be handled is 32bit, and if it is a 64bit CPU, the memory space that can be handled is 64bit.

It seems that the intention of size_t is to abstract these so that they can be expressed in the same source code.

Maximum size_t type

The maximum value of size_t type is defined by SIZE_MAX.

This is a sample that outputs SIZE_MAX in a 64-bit Linux environment. %zu is a format specifier that can output a value of type size_t in a portable way.

#include <stdio.h>
#include <stdint.h>

int main (void) {
  
  printf("%zu\n", SIZE_MAX);
}

This is the output result.

18446744073709551615

If it is less than this value, it is the value of size_t that can be safely used in the processing system. For example, the argument of calloc. However, whether or not the actual memory is sufficient is another matter.

Whether it is safe in terms of specifications and whether it is safe in the actual physical environment are different issues, so let's consider them separately.

size_t type in standard function argument

Standard function arguments include strlen, memcpy function, calloc function, etc. There are many things to receive in size_t type.

size_t strlen (const char * s);
void * memcpy (void * buf1, const void * buf2, size_t n);
void * calloc (size_t n, size_t size);

After all, what should we pass?

Assuming that all environments are 32bit or more, it is safe to handle unsigned 32bit integer type or less in order to operate safely in 32bit environment or more.

However, when dealing with integers, considering that it is handled with the signed 32-bit integer type int32_t, Signed 32-bit integer type maximum value It is better to handle it below.

To write the conclusion, the value passed to the argument of size_t type should be treated as int32_t and should be 0 or more and 2147483647 or less.

The size of the character string or array to be created must also be 2147483647 or less.

Coding this way makes it portable in large environments and significantly reduces the need to wonder or think about size_t.

#include <stdlib.h>

int main (void) {
  int32_t length = 100;
  void * memory_block = calloc (sizeof (int32_t), length);
  free (memory_block);
}

Associated Information