Does the C99/C++11 standard guarantee that sizeof(size_t) == sizeof(void*)
is always true?
size_t f(void* p)
{
return (size_t)(p); // Is it safe?
}
void* f(size_t n)
{
return (void*)(n); // Is it safe?
}
If the system is 32-bit, size of void pointer is 4 bytes. If the system is 64-bit, size of void pointer is 8 bytes.
Size of 'size_t' and size of pointer are completely unrelated, so it is naturally to assume that such platforms exist in general case, regardless of whether they exist in reality.
When you do pointer arithmetic adding or removing one unit means adding or removing the object pointed to size. Thus defining sizeof(void) as 1 helps defining void* as a pointer to byte (untyped memory address).
Since size_t must be an unsigned type, you first need to check explicitly if your float is negative: The behaviour on converting a float that's less than or equal to -1 to an unsigned type is undefined. The second job you need to do is to check that the float is within the upper range of size_t .
No, that is not guaranteed. Use intptr_t
or uintptr_t
to safely store a pointer in an integer.
There are/were architectures where it makes sense for that to be false, such as the segmented DOS memory model. There the memory was structured in 64k segments - an object could never be larger than a segment, so 16-bit size_t
would be enough. However, a pointer had "segment" and "offset" parts, so it would by definition have to be larger than 16 bits to be able to refer to different segments.
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