[英]Print stack in C++
考慮以下代碼:
#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);
}
我期望它 output 堆棧的 startAddress 和 currentAddress 之間的差異。
但是由於某種原因,隨着堆棧的增長,startAddress 似乎也增加了。
我得到 output 像這樣:
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 被修改而不是保持不變?
就像評論中建議的那樣。
它應該是
overflower(startAddress);
比我們得到 output:
174505: stack bottom : 0x7ffda8a3e814, current : 0x7ffda8241844
174506: stack bottom : 0x7ffda8a3e814, current : 0x7ffda8241814
174507: stack bottom : 0x7ffda8a3e814, current : 0x7ffda82417e4
174508: stack bottom : 0x7ffda8a3e814, current : 0x7ffda82417b4
174509: stack bottom : 0x7ffda8a3e814, current : 0x7ffda8241784
174510: stack bottom : 0x7ffda8a3e814, current : 0x7ffda8241754
Segmentation fault
並且可以在分段錯誤之前看到堆棧的大小。
當您這樣做時,您的代碼會調用未定義的行為
uintptr_t(&j) - uintptr_t(startAddress)
因為它計算不相關的變量地址之間的差異(不在同一個數組或類/結構中)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.