Sunday, July 31, 2011

C Gotcha Of The Day: Pointers aren't integers

The C standard is clear that pointers are not required to be convertible to or from an integer.

Friday, July 29, 2011

C Gotcha Of The Day: ptrdiff_t

Excerpt from C99 Draft (AFAIK this has not changed):

The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. If the result is not representable in an object of that type, the behavior is undefined. In other words, if the expressions P and Q point to, respectively, the i-th and j-th elements of an array object, the expression (P) - (Q) has the value i−j provided the value fits in an object of type ptrdiff_t.

That means, while the type size_t is capable of expressing the size of any object, you cannot guarantee that the subtraction of two pointers inside your object will result in defined behavior. That is because ptrdiff_t is signed (so it can give you the direction of the difference) and size_t is unsigned. You can use the macros PTRDIFF_MAX and SIZE_MAX to determine if your subtraction is safe though.