Amine Hajyoussef
Amine Hajyoussef

Reputation: 4430

detect casting from void * to the wrong pointer type

for example:

int *k;
void* c=(void*)&k;
char* x=(char*)c;//outputs a warning or an error
int *g=(int *)c;//compiles successfully(without warnings)

int *gg = malloc(sizeof(int)); //compiles successfully(without warnings)

is it possible to achieve this with gcc or any other compiler?

Upvotes: 1

Views: 366

Answers (1)

NPE
NPE

Reputation: 500277

The short answer is no. Once you've cast your pointer to void*, you've lost all type information.

Let's say you pass the void* into a function in a different translation unit. When compiling that other translation unit, there is no way for the compiler to validate the semantics of anything you do with that pointer.

If you want the compiler to enforce strong typing, don't use void*.

Upvotes: 3

Related Questions