Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void pointer in function parameter

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.

like image 887
Destructor Avatar asked Dec 06 '25 16:12

Destructor


2 Answers

It still compiles fine & crashes at runtime. Why? What is the reason?

Because void* is a technique for removing all type-safety and type checking.

Should I not get the compile time error?

By using void* instead of the correct pointer type int*, you are expressly telling the compiler not to tell you if you are using a type incorrectly or in an undefined way.

Because the correct way to call the function is f(b). right?

That's where your function declaration and contents disagree.

    std::cout<<"(void*)fun is called\n";
    std::cout<<*(int*)a<<'\n';

The contents above imply that a pointer to int should be passed:

void f(void* a)

This declaration implies some pointer should be passed, and no other restrictions are made.

like image 121
Drew Dormann Avatar answered Dec 09 '25 04:12

Drew Dormann


void* can capture any type of pointers, there is no exception to void**

like image 38
Xiaotian Pei Avatar answered Dec 09 '25 06:12

Xiaotian Pei