Search code examples
cpointersgccansi-c

Why isn't GCC's acceptance of void-pointer arithmetic considered a bug?


There are at least three different posts about how void pointer arithmetic is prohibited in C; that gcc 4.8.2 allows it, assuming that a void is of byte size; and how one can turn on extra pedantic warnings to trigger an error. Here is an example:

#include <stdio.h>

/* compile gcc -Wall -o try try.c */

int main() {
  char *str="string";
  void *vp= (void *) str;

  ++vp; /* arithmetic on void point.  huh? */

  printf("%s\n", (char*)vp);
  return 0;
}

My question is about thinking about what a C compiler is supposed to do in case of invalid code. Is it not considered a bug when a compiler does not issue a compile error on invalid code?

And this seems like bizarre behavior for a compiler, anyway — even if gcc does not issue a compile error, at the very least, it could issue a "deprecated" warning with the default compiler flags. And, even with -Wall, it is still not even giving a warning. Huh? It surprised me because gcc seems very mature otherwise and C is not exactly a novel or complex language.


Solution

  • The C standard makes an attempt to perform pointer arithmetic on void* a constraint violation, which means that any conforming C compiler must issue at least one diagnostic message for any program containing such an attempt. The warning may be a non-fatal error; in that case, the compiler may then go on to generate code whose behavior is defined by the implementation.

    gcc, by default, does not warn about pointer arithmetic on void*. This means that gcc, by default, is not a conforming C compiler.

    One could argue that this is a bug, but in its default mode gcc is not a compiler for standard C but for GNU C. (A Fortran compiler's failure to be a conforming C compiler is also not a bug.)

    Carefully chosen command-line options can force gcc to at least attempt to be conforming. For example:

    gcc -std=cXX -pedantic
    

    where XX is one of 90, 99, or 11, will cause gcc to warn about pointer arithmetic on void*. Replacing -pedantic with -pedantic-errors causes it to treat such arithmetic as a fatal error.