cpointersargumentsargument-passingvoid-pointers

void pointer as argument


The following C snippet:

[...] 
void f1(void* a){
  printf("f(a) address = %p \n",a);
  a = (void*)(int*)malloc(sizeof(int));

  printf("a address = %p \n",a);
  *(int*)a = 3;

  printf("data = %d\n",*(int*)a);
}

void f(void){
  void* a1=NULL;
  printf("a1 address = %p \n",a1);

  f1(a1);

  printf("a1 address = %p \n",a1);
  printf("Data.a1 = %d\n",*(int*)a1);
}
[...]

results in

a1 address = (nil) 
f(a) address = (nil) 
a address = 0xb3f010 
data = 3
a1 address = (nil) 
Segmentation fault (core dumped)

Why doesn't a1 keep the address that has been assigned to it in the function?


Solution

  • As this is C, you cannot pass the pointer by reference without passing in a pointer to the pointer (e.g., void ** rather than void * to point to the pointer). You need to return the new pointer. What is happening:

    f(a1);
    

    Pushes the value of the pointer (NULL) as the stack parameter value for a. a picks up this value, and then reassigns itself a new value (the malloced address). As it was passed by value, nothing changes for a1.

    If this were C++, you could achieve what you want by passing the pointer by reference:

    void f(void *&a);