-1

I pass the pointer as a parameter to the function. Inside the function I change it -> it has changed. But after the output is the same as before the function call. The pointer has not changed. What's wrong?

void GetFrom(PVOID lpBuffer){
lpBuffer = malloc(12);
memset(lpBuffer, 0, 12);
printf("%p",pointer); // 0000028D46DECE50
}

PVOID pointer = 0x0;
printf("%p",pointer); // 000000C2628FEFE4
GetFromMap(pointer);
printf("%p",pointer); // 000000C2628FEFE4

In debugging, I saw that the value of the pointer changed inside the function.

2 Answers2

1

Note that lpBuffer = malloc(12) just changes the value of local variable lpBuffer, but this has no effect to the variable which's value has been passed to GetFrom. To change the value of the pointer in the caller`s variable, you need to pass a pointer to that pointer.

void GetFrom(PVOID *lpBuffer){
  *lpBuffer = malloc(12);
  memset(*lpBuffer, 0, 12);
  printf("%p",*lpBuffer); // !=0x0
}

PVOID pointer = 0x0;
GetFromMap(&pointer);
printf("%p",pointer); // should be != 0x0

BTW: instead of malloc and a subsequent memset to 0, you could use calloc, which implicitly fills the allocated memory with 0-

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
0

Inside the function I change it -> it has changed.

Not exactly: the "it" that has changed is the copy of the pointer, not the original pointer that has been passed.

But after the output is the same as before the function call. The pointer has not changed.

That's because you changed a copy, while the pointer retained its original value.

As far as fixing this situation goes, you have one option in C and two options in C++:

  • In C, pass a pointer to a pointer. This will let your function make changes to the pointer passed into it
  • In C++, you can also pass a reference to a pointer. This will produce the same behavior without the need to use dereference operator explicitly.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523