Where do I find the definition of size_t?
According to size_t description on en.cppreference.com size_t
is defined in the following headers :
std::size_t
...
Defined in header <cstddef>
Defined in header <cstdio>
Defined in header <cstring>
Defined in header <ctime>
Defined in header <cwchar>
size_t
is the unsigned integer type of the result of the sizeof operator (ISO C99 Section 7.17.)
The sizeof
operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. The value of the result is implementation-defined, and its type (an unsigned integer type) is size_t
(ISO C99 Section 6.5.3.4.)
IEEE Std 1003.1-2017 (POSIX.1) specifies that size_t
be defined in the header sys/types.h
, whereas ISO C specifies the header stddef.h
. In ISO C++, the type std::size_t
is defined in the standard header cstddef
.
From Wikipedia
The
stdlib.h
andstddef.h
header files define a datatype calledsize_t
1 which is used to represent the size of an object. Library functions that take sizes expect them to be of typesize_t
, and the sizeof operator evaluates tosize_t
.The actual type of
size_t
is platform-dependent; a common mistake is to assumesize_t
is the same as unsigned int, which can lead to programming errors,2 particularly as 64-bit architectures become more prevalent.
From C99 7.17.1/2
The following types and macros are defined in the standard header
stddef.h
<snip>
size_t
which is the unsigned integer type of the result of the sizeof operator
Practically speaking size_t
represents the number of bytes you can address. On most modern architectures for the last 10-15 years that has been 32 bits which has also been the size of a unsigned int. However we are moving to 64bit addressing while the uint
will most likely stay at 32bits (it's size is not guaranteed in the c++ standard). To make your code that depends on the memory size portable across architectures you should use a size_t
. For example things like array sizes should always use size_t
's. If you look at the standard containers the ::size()
always returns a size_t
.
Also note, visual studio has a compile option that can check for these types of errors called "Detect 64-bit Portability Issues".