1

I wonder if the following code will always be compiled so that there are no illegal NULL ptr dereferences?

My concern is that the compiler may check if b->value before first checking if "b" is NULL.

typedef struct
{
    int value;
} mystruct;

int func(mystruct * b)
{
    if((NULL == b) || (b->value == 0))
    {
        return -1;
    }

    printf("value: %d\n", b->value);
}
rich
  • 51
  • 5
  • 1
    possible duplicate of [What is the order of evaluation of statements in a if bracket if(...)?](http://stackoverflow.com/questions/18450585/what-is-the-order-of-evaluation-of-statements-in-a-if-bracket-if). Short answer, `||` is evaluated left to right and will short circuit, the details are in the dup listed. Should have been more careful, this is a C question, this is a [better dup](http://stackoverflow.com/questions/628526/is-short-circuiting-boolean-operators-mandated-in-c-c-and-evaluation-order) – Shafik Yaghmour Aug 28 '13 at 15:24

3 Answers3

2

If b is NULL then (NULL != b) is false, then the second side will be checked. (See Short-Circuit evaluation) and you might get NULL ptr dereferences.

Change || to &&

Maroun
  • 94,125
  • 30
  • 188
  • 241
2

Yes, (NULL != b) will be tested before (b->value == 0).

What you did is called a Short-Circuit Evaluation.

nouney
  • 4,363
  • 19
  • 31
0

You don't have to worry, the second condition won't be executed unless the result isn't already determined by the first condition.

phlogratos
  • 13,234
  • 1
  • 32
  • 37