How to protect in iOS from EXC_BAD_ACCESS in a recursive algorithm

I try to perform some simulations and mathematical operations that are very recursive, and in some cases I overflow the call stack and get the signal EXC_BAD_ACCESS. It is not possible to change the algorithms to iterative form, as there is a lot of outdated code. And limiting the depth of recursion will not be useful, since memory usage is not deterministic.

Is there a way to determine the amount of stack so that I can cancel the operation gracefully?

Is it possible to implement a type of Stack Canary that I can constantly check is not overestimated?

+4
source share
1 answer

If thread safety is not a concern, use a static variable. Something like that:

int recurse(int something) { static int depth = 0; ++depth; if (depth > MAX_DEPTH) { // bail } ... int result = recurse(...); --depth; return result; } 

If the thread safety issue is a problem, you can pass depth as a parameter.

0
source

Source: https://habr.com/ru/post/1384408/


All Articles