C++ cstring

C++ <cstring>: Legacy C-Style Strings

Before C++ introduced the modern std::string class, programmers had to rely on the C language's way of handling text: arrays of characters. The <cstring> library provides functions to manipulate these traditional character arrays.

While you should primarily use <string> in modern C++, you will still encounter <cstring> when dealing with legacy code or interacting with low-level system APIs.


1. How C-Style Strings Work

A C-style string is simply an array of char types that ends with a special invisible character called a null terminator ('\0'). This terminator tells the computer where the string ends.

cstring Example

#include <iostream>
#include <cstring> // Include the C-string library
using namespace std;

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

// strcat appends 'name' to the end of 'greeting' strcat(greeting, name);

cout << greeting << "\n";

// strlen gets the length of the string (excluding the null terminator) cout << "Length: " << strlen(greeting) << "\n";

return 0; }


2. Common Errors with <cstring>

C-style strings are notoriously dangerous and are a leading cause of security vulnerabilities in software.

Error 1: Buffer Overflow

If you declare an array like char name[5]; and try to copy a 10-letter word into it using strcpy(), the function will blindly write data past the end of the array. This corrupts neighboring memory and will likely crash your program (Segmentation Fault). Modern developers prefer strncpy() which limits the amount of data copied.

Error 2: Missing the Null Terminator

If you manually create an array of characters like char word[] = {'H', 'i'}; and print it out, you might see "Hi" followed by absolute gibberish symbols. Because there is no '\0' at the end, C++ doesn't know where the text stops and continues printing random memory data!

Error 3: Comparing with '=='

If you try to compare two C-strings with if (str1 == str2), you aren't comparing the text inside them! You are checking if they occupy the same memory address. To actually compare the text, you must use the strcmp() function.


Exercise

?

What special character must be present at the end of every valid C-style string?