RYUZAKI
RYUZAKI

Reputation: 127

Is there a way to stop implicit pointer conversions to void *

I need to find all such places in my source code where a pointer of any type is implicitly converted to void * or a way to stop these implicit conversions.

For example:

  1. int * to void *
  2. char * to void *
  3. Base * to void *

Is there any gcc warning or error flag which detects all such lines where a pointer is implicitly converted to void *?

Upvotes: 6

Views: 693

Answers (2)

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

You can try this:

gcc -Dvoid="struct doesnotexistanywhere" myfile.c

This will complain about all implicit conversions from and to void*. There will be false positives for at least these cases:

void function( ...
int function(void) { 
(void)statement;

Corresponding messages can be just filtered out with grep, or you can refactor the code to exclude these cases.

Needless to say, even if the compilation somehow succeeds, you should not use the resulting objects. In my experiment, a program that #included stdio.h, memory.h and string.h compiled cleanly, so this is indeed possible, but the standard explicitly disallows this and who knows what kind of code the compiler can generate.

Upvotes: 0

cup
cup

Reputation: 8257

Say you have a simple program like

#include <string.h>
int main()
{
   char* apples = "apples and pears";
   char fruit[1024];
   void* avoid;
   int aint;
   float afloat;

   avoid = &aint;
   avoid = &afloat;
   memcpy(fruit, apples, strlen(apples) + 1);
}

Here is a trick that will tell you where some of the implicit conversions are happening. Add this at the start of the program

#define void double

You will get a lot of compile errors: including where the implicit conversions are happening. It won't spot void* = double* so you'll need to try again with

#define void int

to spot the rest.

Upvotes: 4

Related Questions