01. String Basics & The Null Terminator (\0)

🟢 Difficulty: Beginner | Character Array Buffers, Null Terminators & Read-Only Literals

📖 Definition

In C, a string is defined as a sequence of characters stored in contiguous RAM memory ended by a special sentinel character: the Null Terminator ('\0', ASCII code 0). The null terminator indicates the exact logical end of the string to C runtime functions.

🎯 Why It Is Used

  • Delimiter for Dynamic Lengths: Because C character arrays do not store length metadata, C functions (like printf("%s") or strlen()) iterate character-by-character until hitting '\0'.
  • Memory Efficiency: Null termination eliminates the need to pass explicit size integer structures alongside every string pointer.

⚙️ How It Works: String Literals vs Modifiable Stack Character Arrays

  • Modifiable Stack Character Array (char str[] = "Hello";): Allocates 6 bytes on the local Call Stack (5 letters + '\0'). The characters inside str can be modified freely (e.g. str[0] = 'h';).
  • Read-Only String Literal Pointer (const char *str = "Hello";): Stores the string literal in the binary's Read-Only Data (.rodata) / Text Segment. Attempting to modify characters via str[0] = 'h' causes a Segmentation Fault crash.

📝 Syntax

// 1. Stack Array (Modifiable - reserves 6 bytes automatically)
char greeting[] = "Hello";

// 2. Explicit Character Array Initialization with Null Terminator
char manual[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

// 3. Read-Only String Literal Pointer (Always use 'const char*'!)
const char *immutable_str = "Read-Only Text";

🔀 String Storage Comparison

Declaration Type Memory Segment Modifiable Characters? Total Allocation Byte Size
char str[] = "Code"; Call Stack ✅ Yes (str[0] = 'c';) 5 Bytes (4 chars + '\0')
const char *str = "Code"; Read-Only Text (.rodata) ❌ No (Segmentation Fault!) Pointer size (8B) + 5B in .rodata
char buf[10] = "Code"; Call Stack ✅ Yes 10 Bytes (Pad 0s for rest)

🌱 Beginner Example: Inspecting Null Termination in Memory

#include <stdio.h>

int main(void) {
    char word[] = "C11";

    printf("String Output: %s\n", word);
    printf("=== Character & ASCII Breakdown ===\n");
    for (int i = 0; i <= 3; i++) { // Inspects 0 through 3 (including '\0')
        printf("Index %d | Char: '%c' | ASCII Decimal: %d\n",
               i, (word[i] == '\0') ? '0' : word[i], (int)word[i]);
    }
    return 0;
}

🌼 Intermediate Example: Truncating a String via Null Termination Placement

#include <stdio.h>

int main(void) {
    char message[] = "Full Sentences Are Long";

    printf("Original String : %s\n", message);

    // Insert null terminator at index 4
    message[4] = '\0';

    printf("Truncated String: %s\n", message); // Prints "Full"
    return 0;
}

🌲 Advanced Example: Stack Array vs Read-Only Literal Protection

#include <stdio.h>

void test_modifiable_array(void) {
    char stack_str[] = "cat";
    stack_str[0] = 'b'; // OK: Modifies local stack buffer to "bat"
    printf("Modifiable Stack Array: %s\n", stack_str);
}

void test_readonly_literal(void) {
    const char *ro_str = "cat";
    printf("Read-Only String Literal: %s\n", ro_str);
    // ro_str[0] = 'b'; // CRITICAL: Compile-time error when const is used!
}

int main(void) {
    test_modifiable_array();
    test_readonly_literal();
    return 0;
}

🔍 Line-by-Line Explanation

  • char word[] = "C11";: Reserves 4 bytes on stack: 'C', '1', '1', and '\0'.
  • (int)word[3]: Evaluates to ASCII decimal 0 (the Null Terminator).
  • message[4] = '\0';: Modifies character array in-place, causing printf("%s") to stop scanning at index 4.

💻 Expected Terminal Output

String Output: C11
=== Character & ASCII Breakdown ===
Index 0 | Char: 'C' | ASCII Decimal: 67
Index 1 | Char: '1' | ASCII Decimal: 49
Index 2 | Char: '1' | ASCII Decimal: 49
Index 3 | Char: '0' | ASCII Decimal: 0
Original String : Full Sentences Are Long
Truncated String: Full
Modifiable Stack Array: bat
Read-Only String Literal: cat

⚠️ Common Mistakes & Pitfalls

  • Forgetting the Null Terminator Allocation (+1 Byte): Allocating char buf[5] = "Hello"; leaves no space for '\0', causing string functions to scan past buffer boundaries into garbage memory!
  • Attempting to Mutate Read-Only String Literals: Writing char *s = "text"; s[0] = 'T'; results in a Segmentation Fault crash. Always use const char *s = "text"; for literals.

📌 Important Rules & Limitations

  • A string buffer must always reserve at least 1 extra byte for the null terminator (Length + 1).
  • Always prefix string literal pointers with const char *.

🌐 Multilingual Explanation: English

A C string is a character array ended by a null terminator ('\0', ASCII 0). Always allocate Length + 1 bytes for null storage, and use const char* for read-only string literals.

🌐 Multilingual Explanation: Hindi (Roman Script)

C mein string ek character array hoti hai jo null terminator '\0' par khatam hoti hai. String array banate waqt extra 1 byte '\0' ke liye zaroor add karein (Length + 1).

🌐 Multilingual Explanation: Marathi (Roman Script)

C language madhye string mhanje null terminator ('\0') varni samapta honara char array. Array allocate kartana Length + 1 size dhyava.

❓ Practice Questions

  1. What is the ASCII value of the Null Terminator '\0'?
  2. Why does char str[5] = "Hello"; cause undefined behavior when passed to strlen(str)?
  3. Why does char *s = "text"; s[0] = 'T'; cause a Segmentation Fault crash?

🚀 Practical Coding Challenge

Write a C program named count_vowels_null.c that loops through a character array using a while (str[i] != '\0') loop to count and display the total number of vowels in a given string.

🧭 Navigation & Breadcrumbs

← Module 11 Guide | Next: 02. String Handling Functions →