C中的错误处理策略?

Leo*_*Leo 5 c

鉴于以下代码:

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
}
Run Code Online (Sandbox Code Playgroud)

我想,如果要得到一个编译错误test是有史以来NULL,但我想这是不可能的C.由于我需要在运行时做零检查,什么办法是处理它的最正确的方法是什么?

Jam*_*lis 7

如果您不希望使用空指针调用该函数(即,指针不为null是调用函数的前提条件),则可以在函数顶部使用断言:

assert(test != NULL);
Run Code Online (Sandbox Code Playgroud)

这可以帮助您在调试时查找代码中使用空指针调用函数的位置.

  • @Romain:如果调用函数的前提是指针不是null,那么用空指针调用函数是一个逻辑错误,这正是你想要的行为. (2认同)