I am getting confused with size_t
in C. I know that it is returned by the sizeof
operator. But what exactly is it? Is it a data type?
Let's say I have a for
loop:
for(i = 0; i < some_size; i++)
Should I use int i;
or size_t i;
?
I am getting confused with size_t
in C. I know that it is returned by the sizeof
operator. But what exactly is it? Is it a data type?
Let's say I have a for
loop:
for(i = 0; i < some_size; i++)
Should I use int i;
or size_t i;
?
The manpage for types.h says:
In general, if you are starting at 0 and going upward, always use an unsigned type to avoid an overflow taking you into a negative value situation. This is critically important, because if your array bounds happens to be less than the max of your loop, but your loop max happens to be greater than the max of your type, you will wrap around negative and you may experience a segmentation fault (SIGSEGV). So, in general, never use int for a loop starting at 0 and going upwards. Use an unsigned.
Since nobody has yet mentioned it, the primary linguistic significance of
size_t
is that thesizeof
operator returns a value of that type. Likewise, the primary significance ofptrdiff_t
is that subtracting one pointer from another will yield a value of that type. Library functions that accept it do so because it will allow such functions to work with objects whose size exceeds UINT_MAX on systems where such objects could exist, without forcing callers to waste code passing a value larger than "unsigned int" on systems where the larger type would suffice for all possible objects.If you are the empirical type,
Output for Ubuntu 14.04 64-bit GCC 4.8:
Note that
stddef.h
is provided by GCC and not glibc undersrc/gcc/ginclude/stddef.h
in GCC 4.2.Interesting C99 appearances
malloc
takessize_t
as an argument, so it determines the maximum size that may be allocated.And since it is also returned by
sizeof
, I think it limits the maximum size of any array.See also: What is the maximum size of an array in C?
size_t is unsigned integer data type. On systems using the GNU C Library, this will be unsigned int or unsigned long int. size_t is commonly used for array indexing and loop counting.
size_t
andint
are not interchangeable. For instance on 64-bit Linuxsize_t
is 64-bit in size (i.e.sizeof(void*)
) butint
is 32-bit.Also note that
size_t
is unsigned. If you need signed version then there isssize_t
on some platforms and it would be more relevant to your example.As a general rule I would suggest using
int
for most general cases and only usesize_t
/ssize_t
when there is a specific need for it (withmmap()
for example).