Trapping a code exception

Is there a way to lay a code trap for an event that causes the code to restart? I come across this need often when I am debugging code with pointers and strings. Something gets stomped on and the code restarts, but I don't know where to look for the problem. Can I somehow issue a high level try... catch of some sort? Or is there a better way to debug memory exceptions?

Not without a JTAG debugger and the full Atmel Studio.

The most common technique is to just print the free memory regularly until you see what code block is consuming memory.

Often a code inspection can find where an array has been overrun. Post your code if you want specific advice.

No. The AVR processor does not have support for such things. Even try / except for your exceptions is horribly expensive.

Or is there a better way to debug memory exceptions?

Code defensively (e.g. use snprintf; don't use sprintf).

Post your code.

you can also check if you have successfully allocated memory before using it.

I think the only way in the Arduino world is use of plenty Serial.print/ln statements.

Combine with Serial.flush() when possible; this prevents your code from continuing and hence possibly aborting the Serial output.

There are obviously disadvantages to the approach.

But nothing beats defensive programming.

I’d go with the replies above.
Serial prints, a blinking LED and checking memory.

Post your code here in tags, and we may be able to spot something either in your code, or methods & style.

Or is there a better way to debug memory exceptions?

It’s better not to cause them.

debugging code with pointers and strings

My advice is to pre-allocate all the memory used by your sketch in "setup()". Do not dynamically allocate and release memory in the "loop()" phase of your sketch. The memory manager (or lack thereof) in the arduino is very crude and the use of dynamic memory - as you would on a regular computer - will cause the sketch to "crash" at some point. Using the convenience represented by the "String" class will lead to inconvenience - if not used with extreme care.

//memfree = 1000

char *c1 = new char[98];
//memfree = 900

char *c2 = new char[98];
//memfree = 800

char *c3 = new char[98];
//memfree = 700

delete[] c1;
//memfree = 700

delete[] c2;
//memfree = 700

delete[] c3;
//memfree = 1000

Memory is taken from the "top" and can only be released from the "top" as well. Dynamic memory usage will cause memory fragmentation (unused gaps) and even if there should be enough free memory the crudity of memory manager will not allow you to use it because of that fragmentation.

So.. Reserve whatever you need in "setup()", if your sketch cannot enter the "loop()" phase, you know that the problem is located in "setup()" :slight_smile:

Why allocate? You could also create global array variables.

And it still does not prevent you from touching memory that is not yours :wink: