Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the largest value sizeof(T) can yield?

At first one might think std::numeric_limits<size_t>::max(), but if there was an object that huge, could it still offer a one-past-the-end pointer? I guess not. Does that imply the largest value sizeof(T) could yield is std::numeric_limits<size_t>::max()-1? Am I right, or am I missing something?

like image 965
fredoverflow Avatar asked Oct 31 '11 19:10

fredoverflow


People also ask

How long can an int32 be?

The value of this constant is 2,147,483,647; that is, hexadecimal 0x7FFFFFFF.

What is the sizeof int?

So, the sizeof(int) simply implies the value of size of an integer. Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.

What does sizeof array return?

The sizeof operator returns the number of bytes in a variable type, or the number of bytes occupied by an array.


2 Answers

Q: What is the largest value sizeof(T) can yield?

A: std::numeric_limits<size_t>::max()

Clearly, sizeof cannot return a value larger than std::numeric_limits<size_t>::max(), since it wouldn't fit. The only question is, can it return ...::max()?

Yes. Here is a valid program, that violates no constraints of the C++03 standard, which demonstrates a proof-by-example. In particular, this program does not violate any constraint listed in §5.3.3 [expr.sizeof], nor in §8.3.4 [dcl.array]:

#include <limits>
#include <iostream>
int main () {
 typedef char T[std::numeric_limits<size_t>::max()];
 std::cout << sizeof(T)<<"\n";
}
like image 184
Robᵩ Avatar answered Oct 02 '22 23:10

Robᵩ


If std::numeric_limits<ptrdiff_t>::max() > std::numeric_limits<size_t>::max() you can compute the size of an object of size std::numeric_limits<size_t>::max() by subtracting a pointer to it from a one-past-the-end pointer.

If sizeof(T*) > sizeof(size_t) you can have enough distinct pointers to address each and every single byte inside that object (in case you have an array of char, for example) plus one for one-past-the-end.

So, it's possible to write an implementation where sizeof can return std::numeric_limits<size_t>::max(), and where you can get pointer to one-past-the-end of an object that large.

like image 27
R. Martinho Fernandes Avatar answered Oct 03 '22 00:10

R. Martinho Fernandes