Ravi Singh Ravi Singh - 2 months ago 27
C Question

why segmentation fault (cored dumped )?

I solve a problem on a programming website but when my input n = 2147483647
then its give segmentation fault (core 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;
}
}

Answer

As Weather Vane correctly stated, INT_MAX + 1 gets you undefined behavior.

Here is how you could have figured this out:

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

So you do in fact end up with stack overflow (normally your algorithm shouldn't recur more than 31 times, but due to signed overflow ends up recurring 174693 times before running out of stack).