为什么分段错误(cored dumped)?

时间:2016-09-18 17:28:25

标签: c recursion segmentation-fault

我在编程网站上解决了一个问题但我的输入n = 2147483647 然后它给出分段错误(核心转储)?

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;
  }
}

1 个答案:

答案 0 :(得分: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次)。