Bird
Raised Fist0
Cprogramming~5 mins

Defensive programming practices - Cheat Sheet & Quick Revision

Choose your learning style10 modes available
Recall & Review
beginner
What is defensive programming?
Defensive programming is a way to write code that expects and safely handles unexpected problems or errors to prevent crashes or bugs.
Click to reveal answer
beginner
Why should you check function inputs in C?
Checking inputs helps catch wrong or dangerous values early, avoiding crashes or security problems later in the program.
Click to reveal answer
intermediate
How can you handle errors in C defensively?
Use return codes or error flags to detect problems, and always check these before continuing to avoid unexpected behavior.
Click to reveal answer
intermediate
What is the purpose of assertions in defensive programming?
Assertions check if assumptions in code are true during development. If not, they stop the program to help find bugs early.
Click to reveal answer
beginner
Give an example of a defensive programming practice in C.
Before using a pointer, check if it is NULL to avoid crashes. For example: if (ptr == NULL) { handle error; }
Click to reveal answer
What is a key goal of defensive programming?
AMake code run faster by skipping checks
BAvoid using error handling
CWrite code only for expected inputs
DPrevent program crashes by handling unexpected inputs
Which of these is a defensive programming practice in C?
AIgnoring return values of functions
BUsing global variables without checks
CChecking if pointers are NULL before use
DAssuming inputs are always valid
What does an assertion do in C?
AAutomatically fixes bugs
BChecks if a condition is true and stops the program if not
CRuns only in production code
DSkips error checking
Why should you validate inputs in your functions?
ATo catch invalid data early and avoid errors
BTo reduce code size
CTo ignore user mistakes
DTo make the program slower
Which is NOT a defensive programming practice?
AIgnoring error codes
BChecking for NULL pointers
CUsing assertions during development
DValidating function inputs
Explain what defensive programming is and why it is important in C.
Think about how to keep your program safe from unexpected problems.
You got /3 concepts.
    Describe three defensive programming techniques you can use in C code.
    Consider how to check data and handle errors before they cause crashes.
    You got /3 concepts.

      Practice

      (1/5)
      1. What is the main goal of defensive programming in C?
      easy
      A. To check for errors before they cause problems
      B. To write code faster without testing
      C. To ignore invalid inputs
      D. To make the program run without any comments

      Solution

      1. Step 1: Understand the purpose of defensive programming

        Defensive programming is about preventing errors by checking inputs and conditions early.
      2. Step 2: Identify the correct goal from options

        To check for errors before they cause problems clearly states checking for errors before problems happen, which matches defensive programming.
      3. Final Answer:

        To check for errors before they cause problems -> Option A
      4. Quick Check:

        Defensive programming = check errors early [OK]
      Hint: Defensive programming means catching errors early [OK]
      Common Mistakes:
      • Thinking it means ignoring errors
      • Confusing it with faster coding
      • Believing it removes need for comments
      2. Which of the following is the correct way to check for a NULL pointer before using it in C?
      easy
      A. if (ptr = NULL) { /* use ptr */ }
      B. if (ptr != NULL) { /* use ptr */ }
      C. if (ptr == 0) { /* use ptr */ }
      D. if (ptr = 0) { /* use ptr */ }

      Solution

      1. Step 1: Identify correct NULL pointer check syntax

        In C, to check if a pointer is not NULL, use 'ptr != NULL'. Assignment '=' is wrong here.
      2. Step 2: Analyze each option

        'if (ptr != NULL) { /* use ptr */ }' is correct because it checks that ptr is not NULL before use. B and D use '=' for assignment, setting ptr to NULL/0 and making the condition false. 'if (ptr == 0) { /* use ptr */ }' checks if ptr IS null (equivalent to NULL) and then uses it, causing a null dereference crash.
      3. Final Answer:

        if (ptr != NULL) { /* use ptr */ } -> Option B
      4. Quick Check:

        Use '!=' to compare pointer with NULL [OK]
      Hint: Use '!=' to compare pointer with NULL, not '=' [OK]
      Common Mistakes:
      • Using '=' instead of '==' or '!=' in conditions
      • Confusing NULL with zero without clarity
      • Not checking pointer before use
      3. What will be the output of this C code snippet?
      int *ptr = NULL;
      if (ptr != NULL) {
          printf("Pointer is valid\n");
      } else {
          printf("Pointer is NULL\n");
      }
      medium
      A. Pointer is NULL
      B. Pointer is valid
      C. Compilation error
      D. No output

      Solution

      1. Step 1: Analyze pointer initialization

        The pointer 'ptr' is set to NULL, meaning it points to nothing.
      2. Step 2: Check the if condition

        The condition 'ptr != NULL' is false because ptr is NULL, so the else block runs.
      3. Final Answer:

        Pointer is NULL -> Option A
      4. Quick Check:

        NULL pointer triggers else block [OK]
      Hint: NULL pointer means else block runs [OK]
      Common Mistakes:
      • Assuming NULL pointer is valid
      • Expecting compilation error
      • Thinking no output occurs
      4. Identify the error in this defensive programming snippet:
      void print_length(char *str) {
          if (str = NULL) {
              printf("String is NULL\n");
              return;
          }
          printf("Length: %d\n", strlen(str));
      }
      medium
      A. strlen() cannot be used on strings
      B. Missing semicolon after printf
      C. Using assignment '=' instead of comparison '==' in if condition
      D. Function return type should be int

      Solution

      1. Step 1: Check the if condition syntax

        The condition uses 'str = NULL' which assigns NULL to str instead of comparing it.
      2. Step 2: Understand impact of assignment in condition

        Assignment returns NULL (false), so the if block never runs as intended. It should be 'str == NULL'.
      3. Final Answer:

        Using assignment '=' instead of comparison '==' in if condition -> Option C
      4. Quick Check:

        Use '==' to compare pointers, not '=' [OK]
      Hint: Use '==' to compare, '=' is assignment [OK]
      Common Mistakes:
      • Confusing '=' and '==' in conditions
      • Thinking strlen() is invalid here
      • Ignoring function return type
      5. You want to safely read an integer from user input in C. Which defensive programming practice should you apply?
      hard
      A. Use scanf without checking its return value
      B. Use gets() to read input without validation
      C. Assume input is always correct and proceed
      D. Check scanf's return value and validate the input range

      Solution

      1. Step 1: Understand safe input reading

        Using scanf requires checking its return value to confirm input was read correctly.
      2. Step 2: Validate input range

        After reading, check if the integer is within expected limits to avoid errors later.
      3. Final Answer:

        Check scanf's return value and validate the input range -> Option D
      4. Quick Check:

        Check input success and validity [OK]
      Hint: Always check scanf return and input validity [OK]
      Common Mistakes:
      • Ignoring scanf return value
      • Using unsafe input functions like gets()
      • Assuming user input is always valid
      Recommended

      Ready to prove it?

      Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

      10 questions~5 mineasy hard