...
- shipped with the compiler or operating system.
- from a third-party library.
- developed in-house.
When application-specific code detects an error, it can immediately respond on the spot with a specific action, as in
...
One way to indicate errors is to return a value indicating success or errorsfailure. This compliant solution ensures each function returns a value of type errno_t
, where 0 indicates that no error has occurred.
...
Wiki Markup Source and object code can significantly increase in size, perhaps by as much as 30 to 40 percent \[[Saks 07b|AA. C References#Saks 07b]\].
- All function return values must be checked (see MEM32-C. Detect and handle memory allocation errors, among many others).)
- Functions should not return other values if they return error indicators (see ERR02-C. Avoid in-band error indicators.)
- Any function that allocates resources must ensure they are freed in_cases where errors occur.
...
Instead of encoding status indicators in the return value, each function can take a pointer as an argument, which is used to indicate errors. In the following example, each function uses a errno_t\ *
argument to report errors.
Code Block | ||
---|---|---|
| ||
const errno_t ESOMETHINGREALLYBAD = 1; void g(errno_t * err) { if (err == NULL) { /* Handle null pointer */ } /* ... */ if (something_really_bad_happens) { *err = ESOMETHINGREALLYBAD; } else { /* ... */ *err = 0; } } void f(errno_t * err) { if (err == NULL) { /* Handle null pointer */ } g(err); if (*err == 0) { /* ... do the rest of f ... */ } return 0; } |
...
- Source code size is inflated, though not by as much as in other approaches.
- All error indicators must be checked after calling functions.
- Nesting of function calls that all use this mechanism is problematic.
- Any function that allocates resources must ensure they are freed in cases where errors occur.
- In general, combining registries of different sets of errors is difficult. For example, changing the above this compliant solution code to use
errno
is difficult and bug-prone because the programmer must be precisely aware of when C library functions set and clearerrno
and also must be aware of all validerrno
values before adding new ones. - There are major limitations on calling
f()
from other application-independent code. Becausef()
setsmy_errno
to 0, it may potentially be overwriting a nonzero error value set by another application-independent calling function.
...
Method | Code Increase | Manages Allocated Resources | Automatically Enforceable |
---|---|---|---|
Return value | Big (30—40%) | no | yes |
Address argument | Bigger | no | no |
Global indicator | Medium | no | yes |
| Small | no | n/a |
Risk
...
Assessment
Lack of an error-detection mechanism prevents applications from knowing when an error has disrupted normal program behavior.
...