Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is size_t portable?

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?

like image 566
ant2009 Avatar asked Nov 08 '09 16:11

ant2009


People also ask

Is size_t platform dependent?

I realize that this data type is platform dependent, and is supposedly meant to make code more portable.

What type of variable is size_t?

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.

How much can size_t hold?

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.

Is size_t guaranteed to be unsigned?

Yes, size_t is guaranteed to be an unsigned type. Save this answer.


2 Answers

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.

like image 159
Bastien Léonard Avatar answered Oct 05 '22 01:10

Bastien Léonard


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:

  1. 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.
  2. 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.
  3. Writing a 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.
  4. Sending a 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.

like image 22
D.Shawley Avatar answered Oct 05 '22 01:10

D.Shawley