The title is actually a bit misleading, but I wanted to keep it short. I’ve read about why I should use size_t and I often found statements like this:
size_tis guaranteed to be able to express the maximum size of any object, including any array
I don’t really understand what that means. Is there some kind of cap on how much memory you can allocate at once and size_t is guaranteed to be large enough to count every byte in that memory block?
Follow-up question:
What determines how much memory can be allocated?
Let’s say the biggest object your compiler/platform can have is 4 gb.
size_tthen is 32 bit. Now let’s say you recompile your program on a 64 bit platform able to support objects of size 2^43 – 1.size_twill be at least 43 bit long (but normally it will be 64 bit at this point). The point is that you only have to recompile the program. You don’t have to change all yourints tolong(ifintis 32 bit andlongis 64 bit) or fromint32_ttoint64_t.(if you are asking yourself why 43 bit, let’s say that Windows Server 2008 R2 64bit doesn’t support objects of size 2^63 nor objects of size 2^62… It supports 8 TB of addressable space… So 43 bit!)
Many programs written for Windows considered a pointer to be as much big as a
DWORD(a 32 bit unsigned integer). These programs can’t be recompiled on 64 bit without rewriting large swats of code. Had they usedDWORD_PTR(an unsigned value guaranteed to be as much big as necessary to contain a pointer) they wouldn’t have had this problem.The
size_t“point” is the similar. but different!size_tisn’t guaranteed to be able to contain a pointer!!(the
DWORD_PTRof Microsoft Windows is)This, in general, is illegal:
For example, on the old DOS “platform”, the maximum size of an object was 64k, so
size_tneeded to be 16 bit BUT a far pointer needed to be at least 20 bit, because the 8086 had a memory space of 1 mb (in the end a far pointer was 16 + 16 bit, because the memory of an 8086 was segmented)