talideon.com

Blackout Ireland

October 1, 2007 at 11:15AM Pet Peeves: People who try to increment void pointers.

Here’s a pet peeve of mine that I’ve stumbled across in other people’s code before. Type this into a file called test.cc or test.c, and compile it:

#include <stdio.h>

int main(void) {
    int foo[] = { 1, 2, 3, 4, 5 };
    void* pv;
    pv = foo;
    pv++;
    printf("pv is %p and points to %d\n", pv, *pv);
    return 0;
}

Now, compile it. Here’s what you get:

talisra% gcc test.cc
test.cc: In function `int main()':
test.cc:7: error: ISO C++ forbids incrementing a pointer of type `void*'
test.cc:8: error: `void*' is not a pointer-to-object type

Notice the bit that reads “ISO C++ forbids incrementing a pointer of type ‘void*’”? Or, as C:

talisra% gcc test.c
test.c: In function `main':
test.c:8: warning: dereferencing `void \*' pointer
test.c:8: error: invalid use of void expression

Of course, C doesn’t specify how wide a void is, many compilers treat a void* just like a char* for historical reasons, so pv++ above will increment the pointer by a byte. However, this is really just a compatibility hack because historically char* was used where void* would be used these days, and so is nothing that ought to be depended upon. If you need convincing, as yourself this: what is the result of sizeof(void)? As before, though logically and physically, because void can’t store anything, void has no width. However, in C for compatibility with ancient implementations, it has a width of 1 because it has to behave like char. In C++, it behaves sanely and treats void as having no valid width, refusing to compile it.

Are we clear? So don’t do it.

Comments

1 On October 1, 2007 at 15:53, Revence wrote:

Never committed said sin, maybe because it feels weird. Or because my first C compiler died on meeting it (because it was, in fact, a C++ compiler - Borland C++).