8

There was a question here about equality of sizeof(size_t) and sizeof(void*) and the accepted answer was that they are not guaranteed to be equal.

But at least, must it be that:

sizeof(void*) >= sizeof(size_t)

I think so. Because, take the largest stored object possible in a given C implementation, of size S. Now, the storage area can be thought of as array of bytes of size S. Therefore, there must be a pointer to each byte, and all these pointers are comparable and different. Therefore, the number of distinct elements of type void*, must be at least, the largest number of type size_t, which is unsigned integer type. Thus sizeof(void*) >= sizeof(size_t) .

Is my reasoning making sense or not?

Mark Galeck
  • 5,671
  • 1
  • 23
  • 48
  • Closely related [size_t vs. uintptr_t](https://stackoverflow.com/q/1464174/11082165) – Brian Oct 19 '21 at 03:44
  • 3
    I don't see anything in the standard preventing, say, 48-bit pointers and 64-bit `size_t`. – user2357112 Oct 19 '21 at 03:44
  • https://stackoverflow.com/a/55204639 – Robert Harvey Oct 19 '21 at 03:45
  • 4
    Your logic assumes `size_t` has *exactly* enough bits to represent the largest possible size. It could have more. – user2357112 Oct 19 '21 at 03:46
  • @user2357112 supports Monica oh I see thank you, please make it an answer I will accept it – Mark Galeck Oct 19 '21 at 03:48
  • [Is sizeof(size_t) == sizeof(void*) always true?](https://stackoverflow.com/q/18810800/995714), [Is size of size_t always equal to the size of void * (duplicate)](https://stackoverflow.com/q/19713642/995714) – phuclv Oct 19 '21 at 04:13
  • I'll go ahead and close as dupe, since so far the answer/comments here are the same as in the linked dupe target. – Lundin Oct 19 '21 at 06:59

1 Answers1

0

Is my reasoning making sense or not?

The problem with your reeasoning is that you assume that the size of the largest object possible equals SIZE_MAX. But that's not true. If you do

void* p = malloc(SIZE_MAX);

you will (most likely) get a NULL pointer back.

You may also get warnings like:

main.cpp:48:15: warning: argument 1 value '18446744073709551615' exceeds maximum object size 9223372036854775807 [-Walloc-size-larger-than=]
   48 |     void* p = malloc(SIZE_MAX);
      |               ^~~~~~~~~~~~~~~~

Since the maximum object size isn't (always) SIZE_MAX you can't use the value of SIZE_MAX to argue about the size of pointers.

BTW: Some CPU implementation that uses 64 bit pointers at the SW level may not have 64 bit at the HW level. Instead some bits are just treated as all-ones/all-zeros.

Support Ukraine
  • 39,592
  • 4
  • 35
  • 56