LearnFrenzy
Sign in Take a free test

Decision Making · Find the Error · Question 2

NULL check written after the dereference Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#include <stdio.h>

int is_admin(const char *role) {
    return role[0] == 'A' && role != NULL;
}

int main(void) {
    printf("%d\n", is_admin(NULL));
    return 0;
}
  • A role must not be const
  • B role[0] is read before role is checked for NULL; the guard must come first: role != NULL && role[0] == 'A' Correct
  • C The && should be ||
  • D There is no bug; it prints 0
Correct Answer: Option B

Short-circuit evaluation only protects what comes after the check. Reading role[0] through a null pointer crashes before the NULL test is reached.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links