100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C

Strings in C

Master C strings: null-terminated char arrays, string literals vs char arrays, key string.h functions, and buffer-overflow pitfalls.

Arrays & StringsBeginner15 min readJul 7, 2026
Analogies

1. Introduction

C has no dedicated built-in string data type. Instead, a 'string' in C is simply a sequence of characters stored in a char array, terminated by a special sentinel character called the null character, '\0' (numeric value 0). This null terminator marks the end of the string's content and tells string-handling functions where to stop reading, since the array itself may be larger than the text it holds.

🏏

Cricket analogy: A scoreboard display of '180' stored in a wider digital board that can show up to 3 digits uses a 'stop' signal after the last digit — like C's '\0' — so the display knows not to show trailing blank segments as part of the score.

Because strings are just char arrays under the hood, they inherit all the rules of arrays covered previously — contiguous memory, zero-based indexing, and (crucially) no automatic bounds checking. Almost all standard string manipulation in C is done through functions declared in the <string.h> header, such as strlen, strcpy, strcat, and strcmp.

🏏

Cricket analogy: Since a player's name string is just a char array, indexing name[0] for the first letter follows the same zero-based rules as accessing batsman[0] in a lineup array — and functions like strcmp are needed to alphabetically sort the team roster, just as strcmp compares two strings.

2. Syntax

c
#include <string.h>

// Declaring a string as a char array with a literal initializer
char str1[] = "Hello";          // size automatically becomes 6 (5 chars + '\0')

// Declaring a string with an explicit size
char str2[20] = "Hello";        // remaining bytes are zero-filled

// Pointer to a string literal (read-only)
const char *str3 = "Hello";

// Character-by-character initialization (must add '\0' manually)
char str4[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

3. Explanation

A C string's length as reported by strlen() counts only the visible characters, not the null terminator itself. However, the storage allocated for the string must always be at least strlen(s) + 1 bytes to make room for that terminating '\0'. Forgetting to account for this extra byte is one of the most frequent sources of bugs in C string handling.

🏏

Cricket analogy: strlen('Kohli') returns 5, counting only the letters, not a trailing marker — but the buffer holding the name must be sized 6, just as a nameplate must be cut slightly larger than the printed letters to leave room for the mounting edge.

String Literals vs Char Arrays

There is an important distinction between char str[] = "Hello"; and const char *ptr = "Hello";. In the first form, "Hello" is used to initialize a mutable array; the characters are copied into str's own stack (or static) storage, and individual characters can be modified afterward (str[0] = 'J'; is legal). In the second form, ptr points directly at a string literal, which the compiler typically places in read-only memory; attempting to modify *ptr (e.g. ptr[0] = 'J';) is undefined behavior and often crashes with a segmentation fault on common platforms. As a best practice, string literals accessed through a pointer should always be declared const char * to make this immutability explicit and let the compiler catch accidental writes.

🏏

Cricket analogy: Writing a player's name in chalk on a reusable scoreboard (char str[] = 'Kohli') lets you erase and rewrite a letter anytime, but a name engraved on a permanent trophy plaque (const char *ptr = 'Kohli') can't be altered — trying to chisel a new letter into it risks cracking the plaque, like undefined behavior.

c
char mutable[] = "Hello";
mutable[0] = 'J';           // OK: modifies the array's own copy -> "Jello"

const char *literal = "Hello";
// literal[0] = 'J';        // undefined behavior: attempts to modify a string literal

Common string.h Functions

The <string.h> header provides the core toolkit for C string manipulation. strlen(const char *s) scans forward from s until it finds '\0' and returns the count of characters before it (an unsigned size_t, not including the terminator). strcpy(char *dest, const char *src) copies characters from src into dest, including the terminating null byte, and assumes dest has enough space — it performs no bounds checking whatsoever. strcat(char *dest, const char *src) appends src onto the end of dest (locating the end of dest via its existing null terminator) and again assumes sufficient space in dest. strcmp(const char *s1, const char *s2) performs a lexicographic (dictionary-order) comparison and returns 0 if the strings are equal, a negative value if s1 sorts before s2, and a positive value if s1 sorts after s2.

🏏

Cricket analogy: strlen counts a player's name length like counting letters on a jersey; strcpy copies a new sponsor logo onto a jersey template assuming it fits (no bounds checking); strcat appends a nickname after the surname; strcmp checks if two entered team names match exactly, like verifying a toss call.

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

int main(void) {
    char greeting[50] = "Hello";
    char name[] = ", World!";

    printf("Length: %zu\n", strlen(greeting));   // 5

    strcat(greeting, name);                       // greeting becomes "Hello, World!"
    printf("After strcat: %s\n", greeting);

    char copy[50];
    strcpy(copy, greeting);
    printf("Copy: %s\n", copy);

    if (strcmp(greeting, copy) == 0) {
        printf("greeting and copy are equal\n");
    }
    return 0;
}

Tip: strcmp returns an int whose sign (not magnitude) matters — do not assume it returns -1, 0, or 1 exactly. Always compare the result to 0 (e.g., if (strcmp(a, b) == 0)) rather than checking for a specific value like -1.

Buffer Overflow Pitfalls: strcpy vs strncpy

strcpy and strcat are notoriously unsafe because they copy or append data with no awareness of the destination buffer's actual capacity. If src is longer than the space available in dest, these functions will happily write past the end of the destination array — a classic buffer overflow. This is undefined behavior that can corrupt adjacent stack variables, overwrite a function's saved return address, and has historically been one of the most exploited categories of security vulnerabilities in C programs (e.g., stack-smashing attacks).

🏏

Cricket analogy: strcpy blindly copying a sponsor's overly long name onto a jersey template sized for a short name is like a tailor stitching text that overruns the jersey and bleeds onto the shorts — a buffer overflow that corrupts what's 'adjacent,' just as stack-smashing corrupts nearby memory.

A safer alternative is strncpy(char *dest, const char *src, size_t n), which copies at most n characters from src into dest, preventing the function itself from writing past n bytes. However, strncpy has its own gotcha: if src is longer than or equal to n characters, strncpy does NOT null-terminate dest — you must manually ensure termination, typically by setting dest[n-1] = '\0' after the call. Similarly, strncat(dest, src, n) limits how many characters are appended from src (though the total dest buffer must still be large enough, since strncat does properly null-terminate the result). Modern code should always know the destination buffer size and pass it explicitly to these bounded variants.

🏏

Cricket analogy: strncpy limiting a name copy to n=10 characters is like a scoreboard operator capping a long surname at 10 letters — but if the name is exactly 10 or longer, the operator must manually add a period at the end, or the display keeps bleeding into the next field; strncat, appending a nickname, properly caps and terminates it, like adding a name with an automatic full stop.

Warning: char buf[6]; strcpy(buf, "HelloWorld"); is undefined behavior — "HelloWorld" plus its null terminator needs 11 bytes, but buf only has 6, so strcpy writes 5 bytes past the end of buf. This can silently corrupt other variables or crash the program. Prefer strncpy(buf, src, sizeof(buf) - 1); buf[sizeof(buf) - 1] = '\0'; to guarantee both a bounded copy and proper null-termination.

c
char buf[6];

// UNSAFE: no bounds checking, overflows buf
strcpy(buf, "HelloWorld");

// SAFER: bounded copy, but must manually ensure null-termination
strncpy(buf, "HelloWorld", sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';   // guarantees termination even if src was truncated
printf("%s\n", buf);            // prints "Hello" (truncated, but safe)

4. Example

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

int main(void) {
    char first[20] = "Data";
    char second[20] = "Structures";
    char result[41]; // enough for both strings + separator + '\0'

    // Safely build "Data Structures"
    strncpy(result, first, sizeof(result) - 1);
    result[sizeof(result) - 1] = '\0';

    strncat(result, " ", sizeof(result) - strlen(result) - 1);
    strncat(result, second, sizeof(result) - strlen(result) - 1);

    printf("Combined: %s\n", result);
    printf("Length: %zu\n", strlen(result));

    if (strcmp(first, "Data") == 0) {
        printf("first is exactly \"Data\"\n");
    }

    return 0;
}

5. Output

text
Combined: Data Structures
Length: 15
first is exactly "Data"

6. Key Takeaways

  • A C string is a char array terminated by the null character '\0'; strlen() counts characters excluding this terminator.
  • A buffer of n meaningful characters requires at least n + 1 bytes of storage to hold the trailing '\0'.
  • char str[] = "text"; creates a mutable, independently-owned copy; const char *p = "text"; points to a read-only string literal that must not be modified.
  • strlen, strcpy, strcat, and strcmp are the core string.h functions; strcmp returns 0 for equal strings, not true/false.
  • strcpy and strcat perform no destination bounds checking and are common sources of buffer overflows.
  • strncpy bounds the number of bytes copied but does not guarantee null-termination if the source is too long — you must terminate manually.
  • Always know your destination buffer's size and prefer bounded functions (strncpy/strncat) with explicit manual null-termination for safety.

Practice what you learned

Was this page helpful?

Topics covered

#CProgrammingStudyNotes#Programming#StringsInC#Strings#Syntax#Explanation#String#StudyNotes#SkillVeris#ExamPrep