2016-09-18 52 views
1

我解決了編程網站上的問題,但是當我輸入n = 2147483647 那麼它給出了分段錯誤(核心轉儲)?爲什麼分段故障(cored dumped)?

int integerReplacement(int n) { 
    if(n == 1) 
    return 0; 
    if(n%2 == 0) 
    { 
    return 1+integerReplacement(n/2); 
    } 
    else 
    { 
    int lMin = 1+integerReplacement(n-1);  
    int rMin = 1+integerReplacement(n+1); 
    return lMin<rMin?lMin:rMin; 
    } 
} 
+4

堆棧溢出? – Raman

+9

當遞歸收到你聲明的參數'2147483647'時,那麼'integerReplacement(n + 1);'是*未定義的行爲*,因爲'n'現在超出整數範圍。 –

回答

0

作爲風向標正確地指出,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次)。

+0

thnx這個答案...但有一個疑問是:海灣合作委員會只有31棧整數? –

+0

@RaviSingh在大多數當前體系結構中,整數有31位(加上符號位)。這限制了在達到0或1之前可以將它除以2的次數。 –