作爲風向標正確地指出,INT_MAX + 1
讓你未定義行爲。
這裏是你怎麼會想通了這一點:
gcc -g foo.c
gdb -q ./a.out
(gdb) r
Starting program: /tmp/a.out
Program received signal SIGSEGV, Segmentation fault.
0x00000000004004f5 in integerReplacement (n=<error reading variable: Cannot access memory at address 0x7fffff7fefec>) at foo.c:1
1 int integerReplacement(int n) {
(gdb) bt 6
#0 0x00000000004004f5 in integerReplacement (n=<error reading variable: Cannot access memory at address 0x7fffff7fefec>) at foo.c:1
#1 0x0000000000400522 in integerReplacement (n=-2) at foo.c:6
#2 0x0000000000400534 in integerReplacement (n=-1) at foo.c:10
#3 0x0000000000400522 in integerReplacement (n=-2) at foo.c:6
#4 0x0000000000400534 in integerReplacement (n=-1) at foo.c:10
#5 0x0000000000400522 in integerReplacement (n=-2) at foo.c:6
(More stack frames follow...)
(gdb) bt -10
#174684 0x0000000000400522 in integerReplacement (n=-16777216) at foo.c:6
#174685 0x0000000000400522 in integerReplacement (n=-33554432) at foo.c:6
#174686 0x0000000000400522 in integerReplacement (n=-67108864) at foo.c:6
#174687 0x0000000000400522 in integerReplacement (n=-134217728) at foo.c:6
#174688 0x0000000000400522 in integerReplacement (n=-268435456) at foo.c:6
#174689 0x0000000000400522 in integerReplacement (n=-536870912) at foo.c:6
#174690 0x0000000000400522 in integerReplacement (n=-1073741824) at foo.c:6
#174691 0x0000000000400522 in integerReplacement (n=-2147483648) at foo.c:6
#174692 0x0000000000400547 in integerReplacement (n=2147483647) at foo.c:11
#174693 0x0000000000400567 in main() at foo.c:18
所以你其實做堆棧溢出(通常是您的算法應該不會再發生超過31次,但由於簽訂溢出結束結束在用完堆棧之前重複執行174693次)。
堆棧溢出? – Raman
當遞歸收到你聲明的參數'2147483647'時,那麼'integerReplacement(n + 1);'是*未定義的行爲*,因爲'n'現在超出整數範圍。 –