Given the code below:
typedef struct {int a;} test_t;
arbitrary_t test_dosomething(test_t* test) {
if (test == NULL) {
//options:
//1. print an error and let it crash
//e.g. fprintf(stderr, "null ref at %s:%u", __FILE__, __LINE__);
//2. stop the world
//e.g. exit(1);
//3. return (i.e. function does nothing)
//4. attempt to re-init test
}
printf("%d", test->a); //do something w/ test
}
I want to get a compiler error if test
is ever NULL
, but I guess that's not possible in C. Since I need to do null checking at runtime, what option is the most proper way to handle it?
C does not provide direct support for error handling (also known as exception handling). By convention, the programmer is expected to prevent errors from occurring in the first place, and test return values from functions.
If you never want the function to be called with a null pointer (i.e., the pointer not being null is a precondition to calling the function), you can use an assertion at the top of the function:
assert(test != NULL);
This can help you when debugging to find places in your code where you are calling the function with a null pointer.
We really can't categorically answer this question. It depends highly on what the software is going to be used for. If it's providing radiation, you would want it to print the error and exit(1);
. If you're writing a business app, you probably want to log an error and just return. It's all about the context.
Use setjmp.
http://en.wikipedia.org/wiki/Setjmp.h
http://aszt.inf.elte.hu/~gsd/halado_cpp/ch02s03.html
#include <setjmp.h>
#include <stdio.h>
jmp_buf x;
void f()
{
longjmp(x,5); // throw 5;
}
int main()
{
// output of this program is 5.
int i = 0;
if ( (i = setjmp(x)) == 0 )// try{
{
f();
} // } --> end of try{
else // catch(i){
{
switch( i )
{
case 1:
case 2:
default: fprintf( stdout, "error code = %d\n", i); break;
}
} // } --> end of catch(i){
return 0;
}
I would use an assert at the beginning of the function:
arbitrary_t test_dosomething(test_t* test) {
assert(test != NULL);
printf("%d", test->a); //do something w/ test
}
You won't get a compiler error. But when in development (debugging) your program will halt and point you to that particular assert
in the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With