void demo()
{
printf("demo");
}
int main()
{
printf("%p",(void*)demo);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码打印了函数的地址demo.
因此,如果我们可以打印函数的地址,这意味着该函数存在于内存中并占用其中的一些空间.
那么它在内存中占据了多少空间?
假设我有如下函数:
# cat 003.c
int foo(int a, int b)
{
return a+b;
}
Run Code Online (Sandbox Code Playgroud)
并像这样编译它:
gcc -S 003.c
Run Code Online (Sandbox Code Playgroud)
得到以下汇编结果:
.file "003.c"
.text
.globl foo
.type foo, @function
foo:
.LFB2:
pushq %rbp
.LCFI0:
movq %rsp, %rbp
.LCFI1:
movl %edi, -4(%rbp)
movl %esi, -8(%rbp)
movl -8(%rbp), %edx
movl -4(%rbp), %eax
addl %edx, %eax
leave
ret
.LFE2:
.size foo, .-foo /* size of the function foo, how to get it?*/
Run Code Online (Sandbox Code Playgroud)
上面的最后一行确实得到了函数的大小.编译器在哪里存储大小?我可以使用C或内联asm在我的原始C程序中以某种方式获取函数的大小吗?
我正在处理一些进程间通信的东西,我很好奇是否可以将函数复制到某些共享内存中并从任一进程中运行它。
就像是:
memcpy(shared_memory_address, &func, &func + sizeof(func));
Run Code Online (Sandbox Code Playgroud)
我知道你无法确定函数的大小,但这就是我脑海中突然浮现的想法。
可能重复:
如何以字节为单位获取函数的长度?
我正在制作一个Hooking程序,用于将方法插入到指定的内存部分.
我需要获取本地C++函数的长度,我使用了一个转换来获取函数的位置,但是我如何获得长度?
将
int GetFuncLen()
{
int i = 0;
while((DWORD*)Function+i<max)
{
if((DWORD*)Function+i==0xC3)
{
return i;
}
i++;
}
}
Run Code Online (Sandbox Code Playgroud)
工作?
如何在C++中获取函数的大小?
假设我有一个功能:
void f()
{
/*do something*/
}
Run Code Online (Sandbox Code Playgroud)
..."大小f"是指代码的大小/*do something*/,从指针指示的地址开始f.