C string.h Library Reference
Complete reference for string.h - strlen, strcpy, strcat, strcmp, searching, and memory functions.
Track Your Progress
Sign in to save your learning progress
What You Will Learn
- ✓Measure and copy strings
- ✓Compare and concatenate strings
- ✓Search within strings
- ✓Use memory functions safely
?Why is string.h Essential?
C doesn't have a built-in string type — strings are just character arrays ending with \0. Without string.h, you'd have to write loops for every string operation!
Length
strlen
Copy
strcpy, strncpy
Join
strcat, strncat
Compare
strcmp, strncmp
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).
| Category | Functions |
|---|---|
| Length | strlen |
| Copy | strcpy, strncpy |
| Concatenate | strcat, strncat |
| Compare | strcmp, strncmp, strcasecmp |
| Search | strchr, strrchr, strstr, strtok |
| Memory | memcpy, memmove, memset, memcmp |
02strlen() - String Length
char name[] = "Hello";size_t len = strlen(name);printf("Length: %zu\n", len); // Output: Length: 503String Copy Functions
strcpy() - Copy String
char src[] = "Hello";char dest[20];strcpy(dest, src);printf("%s\n", dest); // Output: Hellostrncpy() - Copy with Limit
char dest[10];strncpy(dest, "Hello World", sizeof(dest) - 1);dest[sizeof(dest) - 1] = '\0'; // Ensure null termination!printf("%s\n", dest); // Output: Hello Worstrncpy() may NOT null-terminate if src is longer than n!
04String Concatenation
strcat() - Append String
char greeting[50] = "Hello";strcat(greeting, " ");strcat(greeting, "World!");printf("%s\n", greeting); // Output: Hello World!strncat() - Append with Limit
char str[20] = "Hello";strncat(str, " World!!!", 6); // Append max 6 charsprintf("%s\n", str); // Output: Hello World05String Comparison
| Function | Prototype | Description |
|---|---|---|
| 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
< 0s1 < s2
0s1 == s2
> 0s1 > s2
1int result;23result = strcmp("apple", "banana"); // < 0 (a < b)4result = strcmp("hello", "hello"); // 0 (equal)5result = strcmp("zoo", "apple"); // > 0 (z > a)67// Compare first 3 characters8result = strncmp("Hello", "Help", 3); // 0 (Hel == Hel)910// Case-insensitive (non-standard, use strings.h)11result = strcasecmp("Hello", "HELLO"); // 0 (equal)1213// Common pattern: checking equality14if (strcmp(input, "exit") == 0) {15 printf("Exiting...\n");16}06String Searching
| Function | Prototype | Description |
|---|---|---|
| strchr() | char *strchr(const char *s, int c) | Find first occurrence of char |
| strrchr() | char *strrchr(const char *s, int c) | Find last occurrence of char |
| strstr() | char *strstr(const char *haystack, const char *needle) | Find substring |
| strtok() | char *strtok(char *str, const char *delim) | Tokenize string |
1char str[] = "hello@world.com";23// Find first '@'4char *at = strchr(str, '@');5if (at) printf("Found @: %s\n", at); // @world.com67// Find last '.'8char *dot = strrchr(str, '.');9if (dot) printf("Found .: %s\n", dot); // .com1011// Find substring12char *found = strstr(str, "world");13if (found) printf("Found: %s\n", found); // world.com1415// Tokenize string16char data[] = "apple,banana,cherry";17char *token = strtok(data, ",");18while (token != NULL) {19 printf("Token: %s\n", token);20 token = strtok(NULL, ","); // NULL for subsequent calls!21}strtok() Modifies String!
strtok() replaces delimiters with \0and uses static memory. Not thread-safe!
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:
✓strncpy() - Safer Copy
// DANGEROUS - strcpy has no bounds checkingchar dest[10];strcpy(dest, "This is way too long!"); // Buffer overflow!// SAFE - strncpy limits copychar 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 wImportant: strncpy may NOT null-terminate if src is longer than n. Always add null terminator manually!
✓strncat() - Safer Concatenation
char dest[20] = "Hello";// Calculate remaining spacesize_t remaining = sizeof(dest) - strlen(dest) - 1;// Safe concatenationstrncat(dest, " World! More text...", remaining);printf("%s\n", dest); // Output: Hello World! More✓snprintf() - Safe Formatted String (from stdio.h)
char buffer[20];int age = 25;char *name = "Alice";// Safe - never overflows bufferint written = snprintf(buffer, sizeof(buffer), "%s is %d years old", name, age);printf("%s\n", buffer); // Output: Alice is 25 yearsprintf("Would need: %d chars\n", written); // Would need: 20 charsUnsafe 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) - 1to 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
| Function | Prototype | Description |
|---|---|---|
| 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 |
1int src[] = {1, 2, 3, 4, 5};2int dest[5];34// Copy array5memcpy(dest, src, sizeof(src));67// Fill with zeros8memset(dest, 0, sizeof(dest));910// Compare memory11if (memcmp(src, dest, sizeof(src)) == 0) {12 printf("Arrays are equal\n");13}1415// 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.
!Code Pitfalls: Common Mistakes & What to Watch For
String handling is one of the most dangerous areas in C programming. code copied without understanding often contains buffer overflow vulnerabilities that can crash programs or create security exploits:
Watch out: Using strcpy() instead of strncpy()
Copied code often looks like:
strcpy(dest, userInput); // Buffer overflow if input > 9 chars!
Always use strncpy() with explicit size limits and manually null-terminate!
Watch out: strncpy() doesn't null-terminate
When source is longer than n, strncpy() doesn't add a null terminator. Code often looks like:
// Missing: dest[sizeof(dest)-1] = '\0';
Code often uses strtok() in thread-unsafe ways
strtok() uses internal static state and modifies the original string. Copied code often uses it in threaded code or on string literals (which causes undefined behavior). Use strtok_r() for thread-safe tokenization.
Beginners often confuse memcpy() with memmove()
Copied code often uses memcpy() for overlapping memory regions, which causes undefined behavior. When source and destination might overlap, always use memmove()!
Frequently Asked Questions
Q: How do I safely copy strings in C?
Use snprintf(dest, sizeof(dest), "%s", src) — it's the safest option as it always null-terminates and limits output. Alternative: strncpy(dest, src, sizeof(dest)-1); dest[sizeof(dest)-1] = '\0'; — but remember to manually null-terminate.
Q: Why doesn't strcmp() return true/false?
strcmp() returns 0 for equal strings (which is "falsy" in C!), negative if first is less, positive if first is greater. This design allows sorting. For equality, use: if (strcmp(a, b) == 0).
Q: What's the difference between strlen() and sizeof()?
strlen() counts characters until null terminator (runtime). sizeof() returns array size in bytes (compile-time). For char str[20] = "Hi": strlen is 2, sizeof is 20.
Q: Can I concatenate strings with the + operator?
No! C doesn't support operator overloading. Using + on strings (char pointers) does pointer arithmetic, not concatenation. Use strcat() or snprintf() instead.
Q: Why does strtok() modify my original string?
strtok() replaces delimiters with null characters to create tokens in-place. If you need to preserve the original, make a copy first: char *copy = strdup(original).
Q: When should I use memset() vs a loop?
Use memset() for filling memory with a single byte value (often 0). It's optimized and faster than loops. However, memset() only works with single-byte patterns — for multi-byte values (like setting all ints to -1), you still need a loop.
Q: How do I safely read a line of input into a string?
Use fgets(buffer, sizeof(buffer), stdin) instead of gets(). fgets() limits input to buffer size, preventing overflow. Remember it includes the newline character— remove it with buffer[strcspn(buffer, "\n")] = 0;
Q: What's the difference between strdup() and strcpy()?
strcpy() copies to an existing buffer you provide. strdup() allocates new memory and copies the string—you must free() it later. strdup() is not part of standard C (it's POSIX) but widely available.
Q: How can I convert a string to uppercase or lowercase?
C has no built-in function for this—you need to iterate and use toupper() or tolower() from ctype.h on each character. Create a helper function that loops through the string and converts each character in place.
11Summary
Key Functions
Length/Copy:
strlen, strcpy, strncpy
Concat/Compare:
strcat, strcmp, strncmp
Search:
strchr, strstr, strtok
Memory:
memcpy, memmove, memset
12String Safety Tips
Always Null-Terminate
C strings must end with '\0'. When copying or building strings manually, always ensure there's room for and inclusion of the null terminator. Off-by-one errors here cause crashes.
Prefer Bounded Functions
Use strncpy() over strcpy(),strncat() over strcat(). Better yet, use snprintf() which handles length and null-termination automatically.
Test Your Knowledge
Related Tutorials
Strings in C
Strings are character arrays ending with \0. Learn to create strings, read them safely, and use string functions like strlen, strcpy, strcmp.
C math.h Library Reference
Complete reference for math.h - power, roots, trigonometry, logarithms, and rounding functions.
C stdlib.h Library Reference
Complete reference for stdlib.h - memory allocation, string conversion, random numbers, sorting, and program control.
Have Feedback?
Found something missing or have ideas to improve this tutorial? Let us know on GitHub!