Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does (size_t)((char *)0) ever not evaluate to 0?

According to the responses in "Why subtract null pointer in offsetof()?" (and my reading of K&R), the C standard doesn't require that (size_t)((char *)0) == 0. Still, I've never seen a situation where casting a null pointer to an integer type evaluates to anything else.

If there is a compiler or scenario where (size_t)((char *)0) != 0, what is it?

like image 854
Bruce Christensen Avatar asked Apr 05 '10 22:04

Bruce Christensen


People also ask

Is Size_t guaranteed to be unsigned?

Yes, size_t is guaranteed to be an unsigned type.

Is Size_t signed or unsigned?

size_t is the unsigned integer type of the result of sizeof , _Alignof (since C11) and offsetof, depending on the data model. The bit width of size_t is not less than 16.

What exactly is Size_t?

The datatype size_t is unsigned integral type. It represents the size of any object in bytes and returned by sizeof operator. It is used for array indexing and counting. It can never be negative. The return type of strcspn, strlen functions is size_t.

What is Uintptr_t?

uintptr_t is an unsigned integer type that is capable of storing a data pointer. Which typically means that it's the same size as a pointer. It is optionally defined in C++11 and later standards.


1 Answers

Well, as you know, the physical representation of null pointer of a given type is not necessarily all-zero bit pattern. When you forcefully convert a pointer (any pointer) value to integer type, the result is implementation defined, but normally (and that's the intent) the numerical value of the pointer - the numerical address - remains unchanged, if possible. This means that if on a given platform a null pointer of type char * is represented by 0xBAADF00D pattern (for example), the above expression will evaluate to 0xBAADF00D, and not to zero. Of course, for that you'd need a platform with non-zero null-pointers. I personally never worked with such platforms, although I heard about a number of real platforms like that out there (like, in the realm of embedded platforms it is not something unusual).

Moreover, as an additional note, null pointer values of different types can have different physical representations, meaning that in theory you can get different values from (size_t) ((int *) 0), (size_t) ((char *) 0) and (size_t) ((double *) 0). But that would be a rather exotic situation, albeit perfectly possible from the point of view of abstract C language.

P.S. Read here (C FAQ) for some examples of actual platforms with non-zero null pointers.

like image 72
AnT Avatar answered Sep 28 '22 08:09

AnT