简体   繁体   English

为什么这种情况会导致段故障?

[英]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. 我认为如果指针为null,则不会评估其余条件。

// 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) 如果ptr && ptr[0] == '1' (错误,因为ptr为空并且ptr[0] == '1'没有得到评估)
  • or ptr[0] == 't' (boom) ptr[0] == 't' (景气)

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. 您有Null ptr &&取消引用了Null ptr,这会导致段错误。

C gives you the option to have statements like if (ptr == NULL) do something; C使您可以选择让语句像if(ptr == NULL)做某事; If it always evaluated a condition to false when a null pointer was detected statements like this wouldn't work. 如果在检测到空指针时始终将条件评估为false,则这样的语句将不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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