Getting error code exited with code -1073741571 while running a C program

Anonymous
2021-05-16T17:38:17.92+00:00

Why am I getting error "exited with code -1073741571" while taking dec's value more than 4539 in the below mentioned C recursive program, but this code is resulting right answer upto the dec's value 4539. So please help me out.

include<stdio.h>

int sum(int);
int main()
{
int fsum, dec;
printf("Enter a number\n");
scanf_s("%d", &dec);
fsum = sum(dec);
printf("Total Sum=%d\n", fsum);
return 0;
}
int sum(int dec)
{
int rsum;

if (dec == 1)
    return 1;
else
    rsum=(sum(dec - 1) + dec);
return rsum;    

}

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,637 questions
{count} votes

Accepted answer
  1. WayneAKing 4,921 Reputation points
    2021-05-17T02:31:41.553+00:00

    As others have noted, you're experiencing stack overflow.
    Calling a function requires stack allocations for
    parameter passing, storing return addresses, etc.

    Recursion can result in using up all of the
    available reserved stack size, which in VS is
    1 MB by default. You can reserve more by setting
    the reserve size in the project properties as already
    described.

    Another way to reserve a larger stack is via the pragma
    directive. Try placing the following pragma at the
    start of your program to reserve a 4 MB stack:

    #pragma comment(linker, "/STACK:4000000")
    

    Note that regardless of the stack size there will
    always be a limit which you may exceed if you do
    deep enough recursion. Therefore recursion should
    be replaced with other techniques if a very large
    number of recursions is expected in normal use.

    Note as well that other activities in a program will
    also be using stack space, so the actual amount
    available for recursion is dependent on the overall
    program requirements. For example, a large local
    static array may take up a lot of stack.

    • Wayne
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Viorel 114.7K Reputation points
    2021-05-16T17:57:26.04+00:00

    Recursive programs require additional memory to organise the calls, this memory block is limited, and it seems that you achieved the limit. To increase it, go to Project Properties, Linker, System, “Stack Reserve Size” and try 2000000, for example.

    Consider non-recursive algorithms too.

    0 comments No comments

  2. Anonymous
    2021-05-17T05:26:43.827+00:00

    Thanks to all for helping me.

    0 comments No comments