0
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int sum(int);

int main() {

    printf("%d", sum(3));

    return 0;
}

int sum(i) {

    int num = 5;

    if (num == i)
    {
        return i;
    }

    else
    {
        return i + sum(i++);
    }

}

This is the program, I'm getting a segmentation error I don't know how to fix it

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • 2
    You have infinite recursion, because `sum(i++)` is calling `sum()` with the old value of `i`, not the incremented value. You want `sum(i+1)`. – Barmar Apr 09 '23 at 22:18
  • You need to study the difference between `i++` and `++i`. Also, you can't use an auto-increment operator in the same expression where you use `i`. See https://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior – Barmar Apr 09 '23 at 22:19
  • 1
    Instead of `sum(i++)` which is giving you the problem, simply use `sum(i + 1)`. Easier to read. Easier to think about. – Fe2O3 Apr 09 '23 at 22:21
  • Hi. On finding Barmar is correct I closed this question with a duplicate set explaining the logic error (post increment) and the resulting stack overflow. – Joshua Apr 09 '23 at 22:38

2 Answers2

1

In C this statement

return i + sum(i++);

has undefined behavior.

Instead you need to write

 return i + sum( i + 1 );

Another problem is that the function declaration that is also its definition

int sum(i) {

is incorrect. You have to write

int sum(int i) {

Pay attention to that the function will have undefined behavior if the initial argument of the function will be greater than the magic number 5.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-3

here

return i + sum(i++);

i will only be incremented after sum returns. So you keep recursing forever and run out of stack.

You need

return i + sum(++i);

EDIT

as other have pointer out the order of which i gets evaluated and when it gets incremented etc is not defined. SO you need

 ++i;
 return i + sum(i);
pm100
  • 48,078
  • 23
  • 82
  • 145
  • 2
    Is this now an undefined behaviour problem? – Weather Vane Apr 09 '23 at 22:20
  • this is UB. The read of (first) `i` and the write of (the 2nd) `i` are not sequenced. – bolov Apr 09 '23 at 22:36
  • @WeatherVane - I k=now understand the comment thanks to bolov – pm100 Apr 10 '23 at 00:16
  • note that even in the case of `return sum(i++);`, `i` would be incremented before `sum` returns (and in fact, before `sum` is entered). There is a sequence point on entry to a function, after evaluation of arguments – M.M Apr 10 '23 at 00:59