Home > Software design >  How to pass void pointer by reference
How to pass void pointer by reference

Time:12-31

I want to have a void* as a function parameter and then inside a function modify that pointer (change it to NULL).

Code below doesn't change memory1 to null after function call. How can I change that.

#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>

void myFree(void**freeMemoryPointer){
    /*some code*/
    *freeMemoryPointer=NULL;
}


int main(){
    void *memory1 = mmap(NULL, getpagesize() , PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);//example
    printf("\nCurrent pointer: %p\n", memory1);
    myFree(memory1);
    printf("\nShould show null: %p\n", memory1);
}

I've also tried this and it works:

myFree((void*)&memory1);

However I need to set void* as a function parameter and not (void*)&void*.

CodePudding user response:

As the question is stated, this is not possible in C.

Passing the value of the pointer memory1 passes a copy of the pointer. The function may use that to access whatever memory1 is pointing at, but it has no way of changing memory1 itself. To do that, the function will need a pointer to memory1, i.e. &memory1.

CodePudding user response:

You could pass the pointer to the pointer to modify it.

void myFree(void**freeMemoryPointer){
    /*some code*/
    *freeMemoryPointer=NULL;
}


int main(void){
    void *memory1 = mmap(NULL, getpagesize() , PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);//example
    printf("\nCurrent pointer: %p\n", memory1);
    myFree(&memory1);
    printf("\nShould show null: %p\n", memory1);
}

Compiles without warning and executes correctly in C & C ( https://godbolt.org/z/fPxfY1YEP https://godbolt.org/z/8razoT9MT)

  • Related