如何使用MSVC每次使malloc返回相同的地址? [英] How to make malloc return the same address every time using MSVC?
问题描述
出于调试目的,我希望 malloc
每次执行程序时都返回相同的地址,但是在MSVC中并非如此.例如:
For debugging purposes, I would like malloc
to return the same addresses every time the program is executed, however in MSVC this is not the case.
For example:
#include <stdlib.h>
#include <stdio.h>
int main() {
int test = 5;
printf("Stack: %p\n", &test);
printf("Heap: %p\n", malloc(4));
return 0;
}
使用cygwin的gcc进行编译时,每次都会获得相同的堆栈地址和堆地址,而在关闭aslr的情况下使用MSVC进行编译...
Compiling with cygwin's gcc, I get the same Stack address and Heap address everytime, while compiling with MSVC with aslr off...
cl t.c /link /DYNAMICBASE:NO /NXCOMPAT:NO
...我每次都获得相同的堆栈地址,但是堆地址会更改.
...I get the same Stack address every time, but the Heap address changes.
我已经尝试添加注册表值 HKLM \ SYSTEM \ CurrentControlSet \ Control \ Session Manager \ Memory Management \ MoveImages
,但是它不起作用.
I have already tried adding the registry value HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\MoveImages
but it does not work.
推荐答案
事实证明,您可能无法从MSVC运行时库中获得确定性行为.C/C ++运行时库的调试版本和生产版本都最终调用了名为 _malloc_base()
的函数,该函数又调用了Win32 API函数 HeapCreate(),记录标记或其他获得确定性行为的方式.
It turns out that you may not be able to obtain deterministic behaviour from the MSVC runtime libraries. Both the debug and the production versions of the C/C++ runtime libraries end up calling a function named _malloc_base()
, which in turn calls the Win32 API function HeapAlloc(). Unfortunately, neither HeapAlloc()
nor the function that provides its heap, HeapCreate(), document a flag or other way to obtain deterministic behaviour.
您可以按照@Enosh_Cohen的建议,在 VirtualAlloc()
之上汇总自己的分配方案,但是随后您将
You could roll up your own allocation scheme on top of VirtualAlloc()
, as suggested by @Enosh_Cohen, but then you'd loose the debug functionality offered by the MSVC allocation functions.
这篇关于如何使用MSVC每次使malloc返回相同的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!