Account

Log in (OpenID enabled)
Register

Finding the Current Address in a C Program

Category: Programming   Tags: , ,

Let’s say for some reason you don’t have a disassembler and you wanted to find the address of a place in your program. This is useful for things like finding out how the size of a function, stack, or some code.

There are many ways to do this.

Probably the easiest way is to use GCC, a free compiler.

int main()
{
    int c;
 
    here:
    c = 5;
 
    printf("Address: %p", **here);
    return 0;
}

In Microsoft Visual Studio you need a function.

__declspec(noinline) void PrintCurrentAddress()
{
    printf("%p", __ReturnAddress);
}

What if you weren’t using GCC or MSVC? Here is the Call trick for x86, and probably trivially adapted to x64.

size_t addr;
__asm
{
    push eax
    call next
    next: pop eax
    mov [addr], eax
    pop eax
}
 
printf("%p", addr);

Supposedly using a “call” without a “ret” is very costly. If this is the case, be sure to wrap the code in a function.

size_t location()
{
    __asm {
        pop eax
        push eax
    }
}

And there you have it! All the information you need in order to find the approximate size of any C code, stack, etc.

  • Reddit
  • Facebook
  • Google Bookmarks
  • RSS

Related posts:

  1. Patching a Program Without Source Code: How to be like the Skype Hacker for Newbies
  2. PHP Sucks: No stable sort
  3. Make a Python JIT compiler without writing a single line of C or 3rd party library
  4. Hash Functions: the modulo prime myth 2
  5. Memory Size of Python Objects

Leave a Comment