Text and buffer boundaries

Lesson 6 of 14 · C memory foundations

A C string is a sequence of char elements ending in the null character \0. A pointer to its first character is commonly used to access it. The terminator is part of the required storage, but not counted by strlen.

char word[5] = "cat";
index:     0   1   2    3     4
value:    'c' 'a' 't'  '\0'  '\0'
                       end of string

The final element is zero because the array initializer fills omitted elements with zero. char word[] = "cat" creates a modifiable four-element array; const char *p = "cat" points to a string literal, which must not be modified. Neither the pointer nor the characters automatically record a usable buffer capacity.

#include <stdio.h>
#include <string.h>
int main(void) {
    char dst[8] = "cat";
    const char *src = "s";
    size_t used = strlen(dst);
    size_t available = sizeof dst - used - 1;
    if (strlen(src) <= available) strcat(dst, src);
    printf("%s: %zu\n", dst, strlen(dst));
    return 0;
}

Output: cats: 4. The capacity calculation includes the terminator. Both inputs must already be valid strings; the regions must not overlap for strcat. strcpy also needs enough space. strncpy can leave its destination unterminated; strncat limits source characters appended, not total buffer size. strcmp compares contents, strchr finds a character, and strstr finds a substring; search functions can return null. Lengths count bytes, not necessarily human-visible characters in UTF-8. snprintf writes at most the specified capacity, including the terminator when capacity is nonzero; check its return for errors or truncation.

Chapter index · Course index