user740521
user740521

Reputation: 1204

Why does this conditional cause a seg fault?

What is the reason for this? I thought that if a pointer is null then the rest of the condition won't be evaluated.

// doesn't work:
char *ptr = somefunction();

if (ptr && ptr[0] == '1' || ptr[0] == 't')
  // ...



// does work:
char *ptr = somefunction();
if (ptr)
    if (ptr[0] == '1' || ptr[0] == 't')
        // ...

Upvotes: 1

Views: 112

Answers (4)

user1399238
user1399238

Reputation: 183

You have Null ptr && dereferenced Null ptr which causes seg fault.

C gives you the option to have statements like if (ptr == NULL) do something; If it always evaluated a condition to false when a null pointer was detected statements like this wouldn't work.

Upvotes: 1

rid
rid

Reputation: 63600

ptr && ptr[0] == '1' || ptr[0] == 't'

means:

  • if ptr && ptr[0] == '1' (false, because ptr is null and ptr[0] == '1' doesn't get evaluated)
  • or ptr[0] == 't' (boom)

Use:

ptr && (ptr[0] == '1' || ptr[0] == 't')

instead.

Upvotes: 5

andrew cooke
andrew cooke

Reputation: 46892

&& has higher precedence than || so the code is equivalent to:

if ((ptr && ptr[0] == '1') || ptr[0] == 't')

and if the first (...&&..) fails, then the second half of || is evaluated.

Upvotes: 3

Mahmoud Al-Qudsi
Mahmoud Al-Qudsi

Reputation: 29579

Your order of evaluation is incorrect. This will work:

if (ptr && (ptr[0] == '1' || ptr[0] == 't'))

Basically, any time you have both && and || in your code, you need a parentheses in there to ensure it does what you mean it to.

Upvotes: 1

Related Questions