Search code examples
cvoid-pointers

Assign address to void pointer passed by reference


First time caller, long time listener. I have a question about some void * pointer-ing and can't seem to find an explanation so maybe someone here can shed some light.

I have a handler function where (among other things) I declare a void pointer and pass it by reference down to some other function:

void some_handler(some args)
{
    void * p_out_data;
    some_other_function(&p_out_data);
    // ... do some stuff with p_out_data after some_other_function stores an address
}

In some_other_function I malloc some memory (how much depends on a few factors), copy a_bunch_of_data into it, and store its address in p_out_data so that some_handler can access a_bunch_of_data:

void some_other_function(void * pp_out_data)   // pp_out_data is the address of p_out_data
{    
    void * p = malloc(d_size); 
    memcpy(p, &a_bunch_of_data, d_size);
    memcpy(pp_out_data, &p, sizeof(p));
}

This all works well. My question is: Why is it that the only way that I can store the memory address returned by malloc() into p_out_data is by using memcpy? I tried to directly store the address in the dereferenced pointer:

*pp_out_data = malloc(d_size);

But I get an error about illegal use of void pointer. I know there are a bunch of rules about void pointers, so I am guessing there's a specific one that applies here?


Solution

  • You're passing a pointer to a pointer, so define the function as such:

    void some_other_function(void **pp_out_data)
    {    
        void * p = malloc(d_size); 
        memcpy(p, &a_bunch_of_data, d_size);
        *pp_out_data = p;
    }