Error handling in C #209
Replies: 5 comments 1 reply
-
I'll start with error cases that come up to my mind:
|
Beta Was this translation helpful? Give feedback.
-
Lots of relevant info and discussion here. https://interrupt.memfault.com/blog/asserts-in-embedded-systems |
Beta Was this translation helpful? Give feedback.
-
To throw something else in the mix: There are definitely arguments to be made for using assert, but I think a lot of those arguments may only be valid when you're developing an entire system or library like an operating system where it maintains extremely low-level control. Ockam, however, is a library that will be used by other developers in their applications and not act as a controller for the entire system. From Ockam's perspective, failing to allocate memory for required internal use will probably constitute a failure for the Ockam library, but it is highly possible Ockam is running as just one of many tasks/threads in a system. In the case of an embedded system, Ockam may not be that high of a priority compared to the other tasks performing more critical operations in the system. In that case if the Ockam library fails the system may want to log the failure and attempt to restart the library at a later point. If we opt to use asserts, we'd end up locking up whatever task/thread we're running in until the OS or the watchdog steps in. By allowing us to pass critical errors back up to the callers of Ockam, it gives the developers the option to assert on failures, deinitialize/reinitialize Ockam as memory is freed or take other appropriate action. The key is we don't force the choice on them. |
Beta Was this translation helpful? Give feedback.
-
@mtm0183 good point. What about taking behaviour of standard libraries and compiler as a baseline? I just realised that alloc indeed doesn't fail if there is no available memory. But what about items 2-4 from the list above? My another point would be that in case of using assertions in code, we can (more likely should) define our own assert macro, which could be more agile, for example crash in debug, but early quit from function in release, or let user customise assert's behaviour, we could even use different types of asserts in different places. |
Beta Was this translation helpful? Give feedback.
-
Currently C libraries don't use asserts and every possible error is handled using function return values. This approach is very safe, but at the cost of convenience at both function implementation and caller-side. My suggestion is to create groups to which we can divide error cases, and decide whether we should use return values or asserts for each of them
Beta Was this translation helpful? Give feedback.
All reactions