ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

C Programming Tutorial• 7 min read

Arrays & Null-Terminated Strings

The \0 null byte, string.h functions (strlen, strcpy, strcmp), and safety

In C, strings are NOT objects. A string is simply a one-dimensional array of char characters terminated by an explicit null byte: '\0' (ASCII code 0).

The Critical Role of the Null Terminator

Without the null terminator '\0', string functions like printf("%s") and strlen() will keep reading past the end of the array into random RAM until encountering a zero or crashing with a Segfault!

Allocating strings: Always allocate N + 1 bytes for a string of length N to accommodate '\0'.

Safety: Avoid strcpy(); use bounded strncpy() or snprintf() to prevent buffer overflow attacks.

Safe String Handling in C
#include <stdio.h>
#include <string.h>

int main(void) {
    // Array size must accommodate 7 chars + 1 null terminator = 8
    char title[32] = "Codexia";
    
    printf("String: %s\n", title);
    printf("Length: %zu bytes\n", strlen(title)); // 7

    // Safe bounded string concatenation
    strncat(title, " Academy", sizeof(title) - strlen(title) - 1);
    printf("Updated: %s\n", title);
    return 0;
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What character marks the end of a string in C?