【发布时间】:2011-01-30 06:15:15
【问题描述】:
我有一个简单的递归函数 RCompare(),它调用一个更复杂的函数 Compare(),它在递归调用之前返回。每个递归级别使用 248 字节的堆栈空间,这似乎比它应该的要多。这是递归函数:
void CMList::RCompare(MP n1) // RECURSIVE and Looping compare function
{
auto MP ne=n1->mf;
while(StkAvl() && Compare(n1=ne->mb))
RCompare(n1); // Recursive call !
}
StkAvl() 是一个简单的堆栈空间检查函数,它将自动变量的地址与存储在静态变量中的接近堆栈末尾的地址的值进行比较。
在我看来,每次递归中添加到堆栈中的唯一东西是两个指针变量(MP 是指向结构的指针)和一个函数调用存储的东西,一些保存的寄存器,基指针,返回地址等,所有 32 位(4 字节)值。不可能是248字节吧?
我不知道如何在 Visual Studio 2008 中以有意义的方式实际查看堆栈。
谢谢
添加反汇编:
CMList::RCompare:
0043E000 push ebp
0043E001 mov ebp,esp
0043E003 sub esp,0E4h
0043E009 push ebx
0043E00A push esi
0043E00B push edi
0043E00C push ecx
0043E00D lea edi,[ebp-0E4h]
0043E013 mov ecx,39h
0043E018 mov eax,0CCCCCCCCh
0043E01D rep stos dword ptr es:[edi]
0043E01F pop ecx
0043E020 mov dword ptr [ebp-8],edx
0043E023 mov dword ptr [ebp-14h],ecx
0043E026 mov eax,dword ptr [n1]
0043E029 mov ecx,dword ptr [eax+20h]
0043E02C mov dword ptr [ne],ecx
0043E02F mov ecx,dword ptr [this]
0043E032 call CMList::StkAvl (41D46Fh)
0043E037 test eax,eax
0043E039 je CMList::RCompare+63h (43E063h)
0043E03B mov eax,dword ptr [ne]
0043E03E mov ecx,dword ptr [eax+1Ch]
0043E041 mov dword ptr [n1],ecx
0043E044 mov edx,dword ptr [n1]
0043E047 mov ecx,dword ptr [this]
0043E04A call CMList::Compare (41DA05h)
0043E04F movzx edx,al
0043E052 test edx,edx
0043E054 je CMList::RCompare+63h (43E063h)
0043E056 mov edx,dword ptr [n1]
0043E059 mov ecx,dword ptr [this]
0043E05C call CMList::RCompare (41EC9Dh)
0043E061 jmp CMList::RCompare+2Fh (43E02Fh)
0043E063 pop edi
0043E064 pop esi
0043E065 pop ebx
0043E066 add esp,0E4h
0043E06C cmp ebp,esp
0043E06E call @ILT+5295(__RTC_CheckEsp) (41E4B4h)
0043E073 mov esp,ebp
0043E075 pop ebp
0043E076 ret
为什么是 0E4h?
更多信息:
class mch // match node structure
{
public:
T_FSZ c1,c2; // file indexes
T_MSZ sz; // match size
enum ntyp typ; // type of node
mch *mb,*mf; // pointers to next and previous match nodes
};
typedef mch * MP; // for use in casting (MP) x
应该是一个普通的旧指针吧?相同的指针在结构本身中,它们只是普通的 4 字节指针。
编辑:添加:
#pragma check_stack(off)
void CMList::RCompare(MP n1) // RECURSIVE and Looping compare function
{
auto MP ne=n1->mf;
while(StkAvl() && Compare(n1=ne->mb))
RCompare(n1); // Recursive call !
} // end RCompare()
#pragma check_stack()
但这并没有改变任何东西。 :(
现在呢?
【问题讨论】:
-
你能做一个 sizeof(MP) 来检查编译器认为它应该为智能指针分配多少内存来显示 MP 的定义吗?
-
它不是“智能指针”。尼克 D 发现了问题。
-
这看起来像一个调试反汇编。发布版本中是否也使用了额外的堆栈空间?您是否尝试更改编译器代码生成选项(项目属性 -> 配置属性 -> C/C++ -> 代码生成)。添加指针变量时使用的额外堆栈空间听起来像是编译器的某种缓冲区溢出检查机制。
标签: visual-c++ mfc stack recursion