Consider following program:
#include <iostream>
void f(void* a)
{
std::cout<<"(void*)fun is called\n";
std::cout<<*(int*)a<<'\n';
}
int main()
{
int a=9;
void* b=(int*)&a;
f(b);
return 0;
}
If I change the function call statement like this:
f(&b);
It still compiles fine & crashes at runtime. Why? What is the reason? Should I not get the compile time error? Because the correct way to call the function is f(b). right? Also, why it is allowed to pass NULL to a function whose parameter is of type (void*)?
Please correct me If I am missing something or understanding something incorrectly.
Because
void*
is a technique for removing all type-safety and type checking.By using
void*
instead of the correct pointer typeint*
, you are expressly telling the compiler not to tell you if you are using a type incorrectly or in an undefined way.That's where your function declaration and contents disagree.
The contents above imply that a pointer to
int
should be passed:This declaration implies some pointer should be passed, and no other restrictions are made.