carveone carveone - 1 year ago 125
C Question

GCC not warning on implicit cast from void * to void **

As void * is the generic pointer, any other type can be implicitly cast to it. However, void ** isn't the generic pointer to pointer thus I would expect a warning from gcc if I implicitly cast to it.

In my code I have a function that takes a pointer to an opaque pointer (because it can be realloced and written back) as:

char *string_store(void **ctxp, const char *str);

If I call this incorrectly as:

void *context;
name = string_store(content, "my name");

instead of
, I would expect gcc to warn about this. But it doesn't. I have -Wall -Wextra options to gcc.

Is there a warning option to turn this on? I can't find it in the gcc docs.

Answer Source

As void * is the generic pointer, any other type can be implicitly cast to it.

You are right that void * is the generic pointer. This means two things:

  • Any other pointer type is implicitly cast to void *;
  • void * is implicitly cast to any other pointer type.

The lack of warning by GCC, therefore, is not because you are implicitly casting to void **, but because you are implicitly casting from void *. A warning, as you request, would be inappropriate in many cases, including this very real use case:

void **ptr = malloc(sizeof *ptr);

As such, I don't believe that it is even desirable. For stricter pointer conversions, use C++, where most implicit void * casts have been removed.

There is, apparently, the -Wc++-compat flag which will warn about this, but you may get very annoyed by it.

Warn about ISO C constructs that are outside of the common subset of ISO C and ISO C++, e.g. request for implicit conversion from void * to a pointer to non-void type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download