简体   繁体   中英

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')
        // ...
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.

&& 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM