Strings & String Library

🔵 C Programming Lesson 10 Intermediate

C does not have a native "String" data type. Instead, strings in C are character arrays terminated by a special null character.

1 The Null Terminator (\0) & Buffer Overflows

Every string in C must end with the null character (**`\0`**), which signals the end of the text. Because of this, a string storing "Java" (4 characters) requires an array size of at least 5 bytes to fit the trailing `\0`:

Memory representation: `['J', 'a', 'v', 'a', '\0']`

⚠️ Warning: Standard string functions (like `strcpy`) do not check array limits. Copying a long string into a small destination array causes a **Buffer Overflow**, which overwrites adjacent memory stack frames and creates significant security vulnerabilities.
2 Core Library Functions in <string.h>

Let's run a program demonstrating common string operations: length, copy, concatenation, and comparison:

C — String Manipulations ▶ Run Code
#include <stdio.h>
#include <string.h>

int main() {
    char greeting[20] = "Hello";
    
    // strlen: get string length (excluding '\0')
    printf("Length of greeting: %lu\n", strlen(greeting));

    // strcat: concatenate strings
    strcat(greeting, " User");
    printf("Concatenated: %s\n", greeting);

    // strcmp: compare strings (returns 0 if equal)
    char pass[10] = "secret";
    if (strcmp(pass, "secret") == 0) {
        printf("Access Granted!\n");
    } else {
        printf("Access Denied!\n");
    }

    return 0;
}
3 Code Challenge
Challenge: Declare a character array representing a name. Write a custom loop (without using `strlen()`) that counts the characters in the array by checking for the null terminator (`\0`), and print the final count.