Search code examples
matlabrecursionstack-overflow

Handle crash when infinite recursion happens


Matlab crash when infinite recursion happens , as in the following code

file: x.m

function x
     y;
end

file: y.m

function y
     x;
end

file: script.m

x;

if the script script.m is executed matlab crash and it must be restarted.

even if I've used try-catch, it's still crashing:

file: script.m

try
x;
catch
    error('stack-overflow');
end

Is there any way to handle such crash omitted from the infinite looping ?


Solution

  • As a quick trick, you can do

    global counter;
    global RecursionDepth;
    counter = 0;
    RecursionDepth = 1000;
    

    somewhere in beginning of your code, then you can do

    function IncrementCounterAndCheckDepth()
    
        global counter;
        global RecursionDepth;
        counter = counter+1;
        if counter > RecursionDepth
        error('stack-overflow');
    else
    disp(RecursionDepth);
        end;
        return;
    

    and insert it whenever necessary to check recursion. You can even add additional info/pass some arguments to it to improve your debugging, and once you are done with debugging, you can remove all globals and define IncrementCounterAndCheckDepth() to do nothing, so performance will not be affected, and for debugging it can be inserted in a lot of places without affecting performance. If you ever need to do additional debugging, you simply turn this function back on and modify is as required to track particular issue - you know it is everywhere in your code.