I am trying to compile and run code snippet bellow, which work in Windows x86 or WOW64 but in Windows x64 he crash with error Access Violation.
Compile with both, gcc and Microsoft C/C++ compilers.
/*Microsoft (R) C/C++ Optimizing Compiler Version 15.00.30729.01 for x64
(x64)cl -W3 -Zi tx.c -Fetx64
(x86)cl -W3 -Zi tx.c -Fetx32
gcc (tdm64-1) 4.7.1
(x64)gcc -m64 -Wall -O2 -o tx64 tx.c
(x86)gcc -m32 -Wall -O2 -o tx32 tx.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int (*fpPUTS)( const char *str ); /*function pointer that takes an const char * as an argument and returns int*/
typedef void (*fpMEMEXEC)( fpPUTS pPuts, char *str ) ;/*function pointer on which first argument is pointer to above function*/
void toMem( fpPUTS pPuts, char *str )
{
pPuts( str );
}
int main(int argc, char* argv[])
{
fpMEMEXEC pMemexec;
pMemexec = (fpMEMEXEC) malloc(4*1024);/* Allocate 4 KB memory space to the function pointer */
memcpy( pMemexec, toMem, 4*1024); /* Copy the content of toMem into newly allocated memory */
pMemexec( puts, "Hello word !!\n"); /* execute it in memory */
return 0;
}
My question is, why this code does not work properly 64-bit environment ?
What rules are not met but should be in order to work properly this code ?