【发布时间】:2020-08-28 08:42:27
【问题描述】:
考虑以下代码:
#include <iostream>
void overflower(const int *startAddress)
{
int j = 0;
std::cout << uintptr_t(&j) - uintptr_t(startAddress)
<< ": stack bottom : " << startAddress << ", current : " << &j <<'\n';
overflower(&j);
}
int main()
{
const int i = 0;
const int* startAddress = &i;
std::cout << uintptr_t(&i) - uintptr_t(startAddress)
<< ": stack bottom : " << startAddress << ", current : " << &i <<'\n';
overflower(&i);
}
我希望它输出堆栈的 startAddress 和 currentAddress 之间的差异。
但是由于某种原因,随着堆栈的增长,startAddress 似乎也增加了。
我得到这样的输出:
18446744073709551568: stack bottom : 0x7ffddc752254, current : 0x7ffddc752224
18446744073709551568: stack bottom : 0x7ffddc752224, current : 0x7ffddc7521f4
18446744073709551568: stack bottom : 0x7ffddc7521f4, current : 0x7ffddc7521c4
18446744073709551568: stack bottom : 0x7ffddc7521c4, current : 0x7ffddc752194
18446744073709551568: stack bottom : 0x7ffddc752194, current : 0x7ffddc752164
18446744073709551568: stack bottom : 0x7ffddc752164, current : 0x7ffddc752134
简而言之。为什么 startAddress 被修改而不是保持不变?
【问题讨论】:
-
因为您使用当前调用的
j变量的地址调用overflower。你的意思是打电话给overflower(startAddress)吗? -
另外,堆栈很可能在您的平台上增长,所以
j - startAddress是负数,当解释为uintptr_t时,这是一个非常大的数字。 -
方向似乎没问题。是的,overflower 应该调用 startAddress。这些错误之一是愚蠢的发现......
标签: c++