Course contentsShow
← C
Lesson 1179 of 1,21916. Practice and ProjectsFree lesson

Edge case testing: Empty strings and zeros

Edge case testing: Empty strings and zeros

What you'll learn: How to identify and test the hidden "boundary" values that often cause C programs to crash or behave unpredictably.

The "Perfect World" Trap

When we write code, we tend to imagine the "Happy Path"—the user types a normal name, a positive number, or a full sentence. However, C is a low-level language that doesn't hold your hand. If your code expects a string but receives an empty one, or expects a divisor but receives zero, it won't just "figure it out." It will likely crash with a segmentation fault or produce "garbage" data. Edge case testing is the art of intentionally trying to break your code with these minimal inputs.

The Empty String: ""

In C, a string is an array of characters ending in a null terminator (\0). An empty string is not "nothing"—it is a memory location containing only that terminator.

  • The Risk: If your logic assumes string[0] is always a letter, or if you use a loop that skips the check for the null terminator, your program might read past the end of the intended memory.

The Zero: 0

Zero is the most dangerous number in programming.

  • The Risk: Mathematical operations (like division or modulo) by zero will crash your program instantly. Additionally, zero is often used to represent "false" or "NULL" in C, leading to logic errors if you don't explicitly handle it as a valid numerical input.

Defensive Testing in Practice

Imagine you are writing a function to calculate the average length of words in a sentence. You must test what happens if the sentence is empty or if the word count is zero.

#include <stdio.h>
#include <string.h>

float calculate_average(int total_chars, int word_count) {
    // Edge case: Division by zero
    if (word_count == 0) {
        return 0.0;
    }
    return (float)total_chars / word_count;
}

void process_input(char *str) {
    // Edge case: Empty string
    if (str[0] == '\0') {
        printf("Error: Input is empty.\n");
        return;
    }
    printf("Processing: %s\n", str);
}

int main() {
    process_input(""); // Testing the empty string
    printf("Avg: %.2f\n", calculate_average(10, 0)); // Testing zero
    return 0;
}

By testing these "extremes" first, you build a safety net that ensures your program is robust enough for the real world.

Key takeaway

Always test your functions with 0, NULL, and empty strings ("") to ensure your logic handles the absence of data as gracefully as the presence of it.