Bird
Raised Fist0
Cprogramming~10 mins

Defensive programming practices - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Defensive programming practices
Start Program
↓
Input Data
↓
Check Input Validity?
No→Handle Error
Yes↓
Process Data Safely
↓
Check for Errors During Processing?
Yes→Handle Error
No↓
Output Result
↓
End Program
The program starts by getting input, checks if input is valid, handles errors if needed, processes data safely, checks for errors again, then outputs the result and ends.
Execution Sample
C
#include <stdio.h>
#include <stdlib.h>

int main() {
    int num;
    if (scanf("%d", &num) != 1) {
        printf("Invalid input\n");
        return 1;
    }
    if (num <= 0) {
        printf("Number must be positive\n");
        return 1;
    }
    printf("You entered: %d\n", num);
    return 0;
}
This code reads an integer, checks if input is valid and positive, handles errors by printing messages, then prints the number.
Execution Table
StepActionInput/ConditionResultNext Step
1Read input with scanfUser enters 'abc'scanf returns 0 (failure)Print 'Invalid input' and exit
2Print error messageInvalid input detectedOutput: 'Invalid input'Program ends with return 1
3Program endsExit code 1No further actionEnd
4Read input with scanfUser enters '5'scanf returns 1 (success), num=5Check if num <= 0
5Check if num <= 0num=5FalsePrint 'You entered: 5'
6Print valid inputnum=5Output: 'You entered: 5'Program ends with return 0
7Program endsExit code 0No further actionEnd
💡 Program stops when input is invalid or after printing the valid number.
Variable Tracker
VariableStartAfter Step 1After Step 4After Step 5Final
numundefinedundefined (scanf failed)555
Key Moments - 3 Insights
Why do we check the return value of scanf?
Because scanf returns the number of successfully read items. If it is not 1, input was invalid. This is shown in execution_table row 1 where scanf fails and we handle the error.
Why do we check if num <= 0 after reading input?
To ensure the number meets expected conditions (positive). This prevents invalid data from causing problems later. See execution_table row 5 where the condition is checked.
What happens if input is invalid?
The program prints an error message and exits early to avoid further errors. This is shown in execution_table rows 2 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'num' after step 4 when input is '5'?
A5
Bundefined
C0
D-1
💡 Hint
Check variable_tracker column 'After Step 4' for 'num'
At which step does the program detect invalid input and stop?
AStep 2
BStep 5
CStep 1
DStep 6
💡 Hint
Look at execution_table row 1 where scanf fails and program decides to stop
If the input was '-3', which step would handle this error?
AStep 1
BStep 5
CStep 4
DStep 6
💡 Hint
Check where the condition 'num <= 0' is evaluated in execution_table
Concept Snapshot
Defensive programming means checking inputs and conditions before using data.
Always verify input success (e.g., scanf return value).
Check data validity (e.g., positive numbers).
Handle errors early by printing messages and exiting.
This prevents crashes and unexpected behavior.
Full Transcript
This example shows defensive programming in C. The program reads an integer from the user. It first checks if the input was successfully read by checking scanf's return value. If input is invalid, it prints an error and stops. If input is valid, it checks if the number is positive. If not, it prints an error and stops. Otherwise, it prints the number and ends normally. This approach avoids problems caused by bad input or unexpected values.

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