Search code examples
cpointersdereference

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

Solution

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