GCC 4.4.1, C99
I am using size_t
, and size_t
is an unsigned int
. However, that depends if you are running 32 bit or 64 bit.
I will be using size_t
to store the size of a buffer.
So I don't think this would be very portable if using across architectures.
Just a question, with using size_t
on either a 32 or 64 bit. What situations would cause the most serious problem?
I realize that this data type is platform dependent, and is supposedly meant to make code more portable.
size_t type is a base unsigned integer type of C and C++ language. It is the type of the result returned by sizeof operator. The type's size is chosen so that it can store the maximum size of a theoretically possible array of any type. On a 32-bit system size_t will take 32 bits, on a 64-bit one 64 bits.
So the minimum maximum value that size_t must be able to hold is 65535, which is 16 bits of precision, and size_t is only defined to be an unknown unsigned integer type.
Yes, size_t is guaranteed to be an unsigned type. Save this answer.
size_t
is guaranteed to be able to hold the number of bytes of any object on your implementation.
That's why the return type of sizeof
is size_t
.
So yes, it's portable.
As others have said, size_t
is correct and perfectly acceptable for storing the result of sizeof()
or the size of any representable object in bytes. What you have to watch out for is the following:
size_t
is the same size as some unsigned integer type. It is not necessarily the same number of bytes as the largest unsigned integer type, unsigned int
, unsigned long
, etc.sizeof(size_t)
is an implementation-defined number of bytes so memcpy
'ing it or assigning into any integer type other than uintmax_t
is a bad idea. I'm not even sure that it is safe to assume that it is of equal size or smaller than uintmax_t
.size_t
value to a binary file and reading it back into a size_t
by another process, on a different machine, or by something compiled with different compiler options can be hazardous to your health.size_t
value across a network and trying to receive it using a sizeof(size_t)
buffer on the other side is rather unsafe.All of these are standard issues with any other integer type except unsigned char
. So size_t
is just as portable as any other integer type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With