Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c - How to make malloc return the same address every time using 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
", &test);
    printf("Heap: %p
", malloc(4));
    return 0;
}

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.

I have already tried adding the registry value HKLMSYSTEMCurrentControlSetControlSession ManagerMemory ManagementMoveImages but it does not work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Both the stack address and the pointer returned by malloc() may be different every time. As a matter of fact both differ when the program is compiled and run on Mac/OS multiple times.

The compiler and/or the OS may cause this behavior to try and make it more difficult to exploit software flaws. There might be a way to prevent this in some cases, but if your goal is to replay the same series of malloc() addresses, other factors may change the addresses, such as time sensitive behaviors, file system side effects, not to mention non-deterministic thread behavior. You should try and avoid relying on this for your tests.

Note also that &test should be cast as (void *) as %p expects a void pointer, which is not guaranteed to have the same representation as int *.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...