尝试将32位代码移植到64位平台时出现内存错误

时间:2013-06-30 14:51:55

标签: c windows 64-bit win64 dep

我正在尝试编译并运行代码片段,它可以在Windows x86或WOW64中运行 但是在Windows x64中,他因访问冲突错误而崩溃。

使用gcc和Microsoft C / C ++编译器进行编译。

/*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;
}

我的问题是,为什么这段代码无法正常运行64位环境? 什么规则没有达到,但应该是为了正确使用这段代码?

1 个答案:

答案 0 :(得分:3)

您的系统可能有DEP - Data Execution Prevention。这意味着每个页面都可以是可写可执行文件,但不能同时写入。

在32位系统上,您需要使用SetProcessDEPPolicy才能为当前进程禁用它。

在64位系统上,您应该使用PAGE_EXECUTE_READWRITE分配 - 类似

pMemexec = VirtualAlloc(0, 4*1024, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

您可能希望看到thisthis个问题,以及this示例。


正如已经指出的那样,保证它会起作用。

  1. 据我所知,C编程语言并不能保证这样的复制会产生合理的可调用功能。
  2. 如果函数不是页面对齐的(这很可能)并且未分配下一页,则会发现自己试图从未分配的内存中读取。所以你必须找到函数的确切时间,不知何故。
相关问题