Reputation: 25
Can someone explain to me why author initializes void pointer to a memory location like this. I am just a begginer and I have never seen notation like this before.
void executeCode(){
char* MEMORY_BUFFER = (char*)VirtualAlloc(NULL, sizeof(someCode), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
memcpy(MEMORY_BUFFER, someCode, sizeof(someCode));
(*(void(*)())MEMORY_BUFFER)();
}
Upvotes: 2
Views: 432
Reputation: 108938
char *MEMORY_BUFFER = /* whatever */;
MEMORY_BUFFER
is a pointer to char. You cannot "execute a string".
You can execute a function if you have a pointer to it.
int (*fxptr)(void) = rand;
printf("%d\n", fxptr()); // execute rand() through the function pointer
printf("%d\n", (*fxptr)()); // dereferencing the function pointer is redundant
The cast
(void(*)())MEMORY_BUFFER
"transforms" (if it were valid) MEMORY_BUFFER
to a pointer to function taking a unspecified number of arguments and returning nothing.
You can call the function through that (assuming it's valid) pointer
((void(*)())MEMORY_BUFFER)();
(*(void(*)())MEMORY_BUFFER)(); // no need to dereference function pointer
Upvotes: 1
Reputation: 1775
It looks like c-style casting of MEMORY_BUFFER
to pointer to function returning void (void(*)())
with dereference and function call. It would be nice to have it simplified as in
typedef fn_ptr void(*)();
(*(fn_ptr)MEMORY_BUFFER)();
Upvotes: 1