Chapter 28Beginner

C string.h Library Reference

Complete reference for string.h - strlen, strcpy, strcat, strcmp, searching, and memory functions.

18 min readUpdated 2024-12-16
string.hstrlenstrcpystrcmpstrcatmemcpystrtok

What You Will Learn

  • Measure and copy strings
  • Compare and concatenate strings
  • Search within strings
  • Use memory functions safely

01Introduction to string.h

📚 What is string.h?

<string.h> provides functions for string manipulation and memory operations. Essential for working with C strings (null-terminated character arrays).

CategoryFunctions
Lengthstrlen
Copystrcpy, strncpy
Concatenatestrcat, strncat
Comparestrcmp, strncmp, strcasecmp
Searchstrchr, strrchr, strstr, strtok
Memorymemcpy, memmove, memset, memcmp

02strlen() - String Length

size_t strlen(const char *str);
str: Null-terminated string
Returns: Number of characters (excludes \\0)
main.c
C
char name[] = "Hello";
size_t len = strlen(name);
printf("Length: %zu\n", len); // Output: Length: 5

03String Copy Functions

strcpy() - Copy String

char *strcpy(char *dest, const char *src);
dest: Destination buffer
src: Source string
Returns: Pointer to dest
main.c
C
char src[] = "Hello";
char dest[20];
strcpy(dest, src);
printf("%s\n", dest); // Output: Hello

strncpy() - Copy with Limit ⭐

char *strncpy(char *dest, const char *src, size_t n);
dest: Destination buffer
src: Source string
n: Max chars to copy
main.c
C
char dest[10];
strncpy(dest, "Hello World", sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0'; // Ensure null termination!
printf("%s\n", dest); // Output: Hello Wor

⚠️ strncpy() may NOT null-terminate if src is longer than n!

04String Concatenation

strcat() - Append String

char *strcat(char *dest, const char *src);
main.c
C
char greeting[50] = "Hello";
strcat(greeting, " ");
strcat(greeting, "World!");
printf("%s\n", greeting); // Output: Hello World!

strncat() - Append with Limit

char *strncat(char *dest, const char *src, size_t n);
main.c
C
char str[20] = "Hello";
strncat(str, " World!!!", 6); // Append max 6 chars
printf("%s\n", str); // Output: Hello World

05String Comparison

FunctionPrototypeDescription
strcmp()int strcmp(const char *s1, const char *s2)Compare two strings
strncmp()int strncmp(s1, s2, size_t n)Compare first n chars
strcasecmp()int strcasecmp(s1, s2)Case-insensitive compare

📊 Return Values

< 0

s1 < s2

0

s1 == s2

> 0

s1 > s2

strcmp_example.c
C
1int result;
2
3result = strcmp("apple", "banana"); // < 0 (a < b)
4result = strcmp("hello", "hello"); // 0 (equal)
5result = strcmp("zoo", "apple"); // > 0 (z > a)
6
7// Compare first 3 characters
8result = strncmp("Hello", "Help", 3); // 0 (Hel == Hel)
9
10// Case-insensitive (non-standard, use strings.h)
11result = strcasecmp("Hello", "HELLO"); // 0 (equal)
12
13// Common pattern: checking equality
14if (strcmp(input, "exit") == 0) {
15 printf("Exiting...\n");
16}

07Secure String Functions (Buffer Overflow Prevention)

🛡️ Why Secure Functions?

Functions like strcpy() and strcat() are dangerous because they don't check buffer sizes. This can cause:

Buffer Overflow: Writing past array bounds
Security Vulnerabilities: Hackers can exploit overflows

✅ strncpy() - Safer Copy

char *strncpy(char *dest, const char *src, size_t n);
dest: Destination buffer (must be large enough)
src: Source string to copy from
n: Maximum number of characters to copy
Returns: Pointer to dest
main.c
C
// DANGEROUS - strcpy has no bounds checking
char dest[10];
strcpy(dest, "This is way too long!"); // Buffer overflow!
// SAFE - strncpy limits copy
char safe_dest[10];
strncpy(safe_dest, "This is way too long!", sizeof(safe_dest) - 1);
safe_dest[sizeof(safe_dest) - 1] = '\0'; // Always null-terminate!
printf("%s\n", safe_dest); // Output: This is w

💡 Important: strncpy may NOT null-terminate if src is longer than n. Always add null terminator manually!

✅ strncat() - Safer Concatenation

char *strncat(char *dest, const char *src, size_t n);
dest: Destination string (must have space)
src: String to append
n: Maximum characters to append
Returns: Pointer to dest
main.c
C
char dest[20] = "Hello";
// Calculate remaining space
size_t remaining = sizeof(dest) - strlen(dest) - 1;
// Safe concatenation
strncat(dest, " World! More text...", remaining);
printf("%s\n", dest); // Output: Hello World! More

✅ snprintf() - Safe Formatted String (from stdio.h)

int snprintf(char *str, size_t size, const char *format, ...);
str: Destination buffer
size: Buffer size (including null terminator)
format: Format string (like printf)
Returns: Characters that would be written (excluding null)
main.c
C
char buffer[20];
int age = 25;
char *name = "Alice";
// Safe - never overflows buffer
int written = snprintf(buffer, sizeof(buffer), "%s is %d years old", name, age);
printf("%s\n", buffer); // Output: Alice is 25 years
printf("Would need: %d chars\n", written); // Would need: 20 chars

🔴 Unsafe vs 🟢 Safe Functions

Unsafe ❌Safe ✅Why Safer?
strcpy()strncpy()Limits bytes copied
strcat()strncat()Limits bytes appended
sprintf()snprintf()Limits output size
gets()fgets()Limits input size

💡 Best Practices for Safe String Handling

  • • Always use sizeof(buffer) - 1 to leave room for null terminator
  • • Prefer snprintf() over sprintf() for formatted strings
  • • Always manually null-terminate after strncpy()
  • • Never use gets() - it's so dangerous it was removed from C11!

08Memory Functions

FunctionPrototypeDescription
memcpy()void *memcpy(void *dest, const void *src, size_t n)Copy n bytes
memmove()void *memmove(void *dest, const void *src, size_t n)Copy (handles overlap)
memset()void *memset(void *ptr, int value, size_t n)Fill memory with byte
memcmp()int memcmp(const void *s1, const void *s2, size_t n)Compare n bytes
memory_funcs.c
C
1int src[] = {1, 2, 3, 4, 5};
2int dest[5];
3
4// Copy array
5memcpy(dest, src, sizeof(src));
6
7// Fill with zeros
8memset(dest, 0, sizeof(dest));
9
10// Compare memory
11if (memcmp(src, dest, sizeof(src)) == 0) {
12 printf("Arrays are equal\n");
13}
14
15// Overlapping memory: use memmove!
16char str[] = "Hello World";
17memmove(str + 6, str, 5); // "Hello Hello"

💡 memcpy vs memmove

Use memmove() when source and destination may overlap. memcpy() is faster but undefined for overlapping regions.

09Summary

🎯 Key Functions

Length/Copy:

strlen, strcpy, strncpy

Concat/Compare:

strcat, strcmp, strncmp

Search:

strchr, strstr, strtok

Memory:

memcpy, memmove, memset

10Next Steps

Learn about mathematical functions: