64,654
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#ifdef _MSC_VER
#define GET_STACK_FRAME( __ebp__ ) do { __asm { mov __ebp__ , ebp } } while(0)
#else
#define GET_STACK_FRAME( __ebp__ ) __asm__ ("movl %%ebp , %0":"=m"(__ebp__) )
#endif
void* getNextFrame( void* xFrame , void** nextFrame )
{
if( nextFrame )
*nextFrame = ((void**)xFrame)[0];
return ((void**)xFrame)[1];
}
void* startUpCode = NULL;
void foobar()
{
int depth = 0;
void *xFrame , *xReturnAddress;
GET_STACK_FRAME( xFrame );
for( ;( xReturnAddress = getNextFrame( xFrame , &xFrame ) ) != startUpCode ; ++depth )
;
printf( "%d\n" , depth );
}
void dummyCaller()
{
if( rand()&15 )
dummyCaller();
else
foobar();
}
int main()
{
void* xMainFrame;
srand( time(NULL) );
GET_STACK_FRAME( xMainFrame );
startUpCode = getNextFrame( xMainFrame , NULL );
foobar();
dummyCaller();
return 0;
}
int fc(int a,int b)
{
int c;
if(main直接调用我)
{
c=a*b+a;
}
else if(fc3调用了fc2再调用我)
{
c=a*b;
}
else if(fc2调用我)
{
c=a*b+b;
}
int n=(main调用了N个函数才调用到我,取此N值)
printf("距离main的层数:%d\r\n",n);
return c;
}
int fc2(int a)
{
return fc(a,a+2);
}
int fc3(int a)
{
return fc2(a,a-1);
}
main()
{
fc(1,2);
fc2(5);
fc3(10);
}
----------------------
int fc(int a,int b)
{
int c=a+b;
if(我已经递归了8次了)//要用堆栈展开做递归计数。
{ return c; }
return fc(c,a);
}
int fc()
{
...
if(直接调用我的是fc2)
{
让fc2本身也返回;
}
else
{
...
}
}
int fc()
{
...
if(某种情况)
{
返回n层
}
else if(某种情况2)
{
返回直到是另一函数fck的环境
...
}
}