简体   繁体   中英

Why i'm getting Segmentation fault (core dumped) in the following code?

In this code making use of a-- and b++ shows Segmentation fault, but if am giving --a and ++b its working, why?!

add(a,b)
{ 
   if (a==0)
       return b;
    else
       return add(a--,b++); //why this line didn't work??! 
}

The post increment and decrement operators actually increment or decrement the values after the expression is evaluated, means it will change the values of a and b after they have been passed to the function.

This way you'll end up passing unchanged values of a and b to add () function all the time which will cause a stack overflow (causing the segmentation fault) as this is essentially a recursive function which never meets the returning condition.

OTOH, if you use pre-increment or decrement operator, the values of a and b will get decreased before they are passed to recursive add () call, thereby meeting the return condition, hence your program operates as expected.

That said, you should specify the return type of a function, for example, in this case, int .

Yes the issue is because you do a post increment/decrement, adding or subtracting AFTER going into the function. You actually go into an endless loop that probably gives you a segmentation fault.

Also, your function definition is wrong.

This should be your code:

int add(int a,int b)
{ 
   if (a==0)
       return b;
    else
       return add(--a,++b);
       //or
       //return add(a-1,b+1);    
}

Segmentation fault relates to accessing memory outside of the allocated bounds. Currently, your function will cause a StackOverflow because the add function is called endlessly untill the stack pointer can no longer be pushed further.

There is most likely something else, which you didn't expose here, in your code that causes the SegmentationFault.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM