Your system probably has DEP - Data Execution Prevention. This means that every page can be either writable or executable, but not both.
On 32bit systems, You will need to use SetProcessDEPPolicy in order to disable it for the current process.
On 64bit systems, you should allocate using PAGE_EXECUTE_READWRITE - something like
pMemexec = VirtualAlloc(0, 4*1024, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
You probably want to see this and this questions, and this example.
As has been pointed out, this does not guarantee it will work.
- As far as I am aware, the C programming language make no guarantee that such copying will make a sensibly callable function.
- If the function is not page-aligned (which is probable) and the next page is not allocated, you find yourself trying to read from an unallocated memory. So you will have to find exactly how long the function is, somehow.