Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is sizeof(size_t) == sizeof(void*) always true?

Tags:

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?
}
like image 743
xmllmx Avatar asked Sep 15 '13 09:09

xmllmx


People also ask

What does sizeof void * return?

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.

Is Size_t the same size as a pointer?

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.

Why is sizeof void 1?

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).

Can Size_t be float?

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 .


1 Answers

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.

like image 75
Angew is no longer proud of SO Avatar answered Sep 22 '22 14:09

Angew is no longer proud of SO