Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
Announcements
FPGA community forums and blogs on community.intel.com are migrating to the new Altera Community and are read-only. For urgent support needs during this transition, please visit the FPGA Design Resources page or contact an Altera Authorized Distributor.

Recursion limitations

hgr_iwf
Beginner
1,071 Views
Hello!

Are there limitations by calling recursive subroutines?

I tried the following very simple program and after 18421 times of calling the routine I got an error message.

Code:
-------
(main program)

implicit none
integer(2) :: n
n = 1
write(*,*) 'begin'
call factorial(n)
END

(recursive subroutine)
RECURSIVE SUBROUTINE factorial (n)
integer(2), intent(inout) :: n
write(*,*) 'n: ', n
n = n + 1
call factorial (n)
END SUBROUTINE

Error message:
------------------
Unhandled exception at 0x7d61f448 in test.exe: 0xC0000005: Access violation writing location 0x00030e3c.
There is no source code available for the current location.

Thanks for your help,
Hannes
0 Kudos
2 Replies
GVautier
New Contributor III
1,071 Views
Quoting - hgr_iwf
Hello!

Are there limitations by calling recursive subroutines?

I tried the following very simple program and after 18421 times of calling the routine I got an error message.

Code:
-------
(main program)

implicit none
integer(2) :: n
n = 1
write(*,*) 'begin'
call factorial(n)
END

(recursive subroutine)
RECURSIVE SUBROUTINE factorial (n)
integer(2), intent(inout) :: n
write(*,*) 'n: ', n
n = n + 1
call factorial (n)
END SUBROUTINE

Error message:
------------------
Unhandled exception at 0x7d61f448 in test.exe: 0xC0000005: Access violation writing location 0x00030e3c.
There is no source code available for the current location.

Thanks for your help,
Hannes
Hello

When you call a recursive function, it takes space in the stack at each call (in your case dont forget that "write" use stack space). So it comes a point where the stack is full.

In your case, you don't have exit condition so it cannot ends. So the program will crash on stack overflow or integer overflow when "n" will reach 2^31.
0 Kudos
TimP
Honored Contributor III
1,071 Views
Quoting - gvautier
Hello

When you call a recursive function, it takes space in the stack at each call (in your case dont forget that "write" use stack space). So it comes a point where the stack is full.

In your case, you don't have exit condition so it cannot ends. So the program will crash on stack overflow or integer overflow when "n" will reach 2^31.
n was declared with KIND=2, so bad things should happen much sooner than that.
0 Kudos
Reply