gpt4 book ai didi

c - 为什么段错误(核心转储)?

转载 作者:太空宇宙 更新时间:2023-11-04 04:28:01 27 4
gpt4 key购买 nike

我在一个编程网站上解决了一个问题,但是当我输入 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;
}
}

最佳答案

正如 Weather Vane 正确指出的那样,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 次)。

关于c - 为什么段错误(核心转储)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39560602/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com