c++cmemory

Memory hacking / memory allocation : why does this work and how?


What i know is you look for some address of of some variables in the software you're trying to manipulate . And once you find it you then try to find the "base pointer" for it so no matter where the process is , you can still access those variables.I mean when the process is restarted the variables would have different addresses , but still you know where they are .

Now what i don't get is why is this possible ?

lets say i do this in C++ :

int *x = (int*)malloc(sizeOf(int));

isn't that dynamic ? and shouldn't x be placed in a "random" address that was free at the time ? Basically what I'm asking about is where is x really when that code is executed?

EDIT : i mean like usually variables like health are stored in addresses like game.exe + 0000caff , and then you can always find them there .


Solution

  • The following is from the perspective of 32-bit x86 architecture, other architectures may do things differently. Also, I assumed that the single line of code was in a function.

    First remember what the declaration int* x means, loosely it can be read as "the variable x will contain the address of an integer"

    The variable x is a local (or automatic variable) which means its location is determined at compile time, and storage space for it is allocated when the function is activated (most likely on the stack).

    The value contained in x is a dynamic address (and probably located on the heap).

    So what you have is a binding between the variable x and some location in the activation frame of the function. Excusing the poor ASCII art, something like this (address are notional, also remember that the stack grows down):

                 ~            ~
                 |            |
                 +------------+
        0x04000  |            |<----   ebp
                 +------------+
                 |            |
                 +------------+
        0x03ff8  |     x      | 
                 +------------+
                 |            |
                 +------------+
        0x03ff0  |            |<----  esp
                 +------------+
    

    Now we have to register values ebp (the extended base pointer) and esp (the extended stack pointer) that define the bottom and top of the activation frame on the stack. So in assembly, if you want to locate where x is stored is is based on an offset from the base pointer.

    Another way of thinking about it that the variable name x is an alias for the memory location epb-8. Because, this is how the compiler lays out memory the storage location for x will always be located at the same offset from the base pointer.

    Now, during multiple runs the value of the base pointer might change, as long as I can find the base pointer for the activation frame, I can find the storage location for x and fiddle with it.