Is the difference of two non-void pointer variables defined (per C99 and/or C++98) if they are both NULL
valued?
For instance, say I have a buffer structure that looks like this:
struct buf {
char *buf;
char *pwrite;
char *pread;
} ex;
Say, ex.buf
points to an array or some malloc'ed memory. If my code always ensures that pwrite
and pread
point within that array or one past it, then I am fairly confident that ex.pwrite - ex.pread
will always be defined. However, what if pwrite
and pread
are both NULL. Can I just expect subtracting the two is defined as (ptrdiff_t)0
or does strictly compliant code need to test the pointers for NULL? Note that the only case I am interested in is when both pointers are NULL (which represents a buffer not initialized case). The reason has to do with a fully compliant "available" function given the preceding assumptions are met:
size_t buf_avail(const struct s_buf *b)
{
return b->pwrite - b->pread;
}
See Question&Answers more detail:os