0
0
Cprogramming~5 mins

Defensive programming practices

Choose your learning style9 modes available
Introduction

Defensive programming helps your code avoid mistakes and crashes by checking for problems early.

When reading input from users or files that might be wrong.
When working with pointers that could be NULL.
When dividing numbers to avoid dividing by zero.
When handling memory allocation to check if it worked.
When writing functions that others will use to prevent misuse.
Syntax
C
if (condition) {
    // handle error or unexpected case
}

Use if statements to check for bad inputs or errors.

Always check pointers before using them to avoid crashes.

Examples
This checks if a pointer is NULL before using it.
C
if (ptr == NULL) {
    printf("Pointer is NULL, cannot proceed.\n");
    return;
}
This prevents division by zero errors.
C
if (denominator == 0) {
    printf("Cannot divide by zero!\n");
    return;
}
This checks if memory allocation worked before using the pointer.
C
int *p = malloc(sizeof(int));
if (p == NULL) {
    printf("Memory allocation failed.\n");
    exit(1);
}
Sample Program

This program shows defensive checks for division by zero and memory allocation failure.

C
#include <stdio.h>
#include <stdlib.h>

int divide(int a, int b) {
    if (b == 0) {
        printf("Error: Cannot divide by zero.\n");
        return 0; // Return safe value
    }
    return a / b;
}

int main() {
    int x = 10;
    int y = 0;
    int result = divide(x, y);
    printf("Result: %d\n", result);
    
    int *ptr = malloc(sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }
    *ptr = 5;
    printf("Value pointed by ptr: %d\n", *ptr);
    free(ptr);

    return 0;
}
OutputSuccess
Important Notes

Always check inputs and pointers before using them.

Return safe values or stop the program if something goes wrong.

Defensive programming makes your code stronger and easier to fix.

Summary

Defensive programming means checking for errors before they cause problems.

Use if statements to catch bad inputs or NULL pointers.

This helps your program avoid crashes and unexpected behavior.