Scan the code to follow Chip Dynamics and say goodbye to “chip” blockage!

Search WeChat
Chip Dynamics
The C language does not have a true string type; instead, it uses a character array + ‘\0’ (null character) to represent a string.
Thus, <string.h> provides a group of “text wizards” (string functions) to help us manipulate these fragile character arrays.
strlen(): How long is your string?
Function: Calculates the length of the string (excluding ‘\0’).
Example:
#include <stdio.h>
#include <string.h>
int main(){
char str[] = "Hello";
printf("Length: %zu\n", strlen(str)); // Outputs 5 (not 6!)
return 0;
}
⚠️ Pitfall Guide:
-
strlen does not count ‘\0’, but sizeof does!
char str[10] = "Hi";
printf("%zu\n", strlen(str)); // 2
printf("%zu\n", sizeof(str)); // 10 (total size of the array)
-
If the string does not have ‘\0’, strlen will keep reading until a memory crash!
char bad_str[3] = {'A', 'B', 'C'}; // No '\0'!
printf("%zu\n", strlen(bad_str)); // Random number or crash
strcpy(): String copy, but beware of buffer overflow
Function: Copies the src string to dest.
Example:
char dest[10];
strcpy(dest, "Hello"); // Correct
strcpy(dest, "Hello, World!"); // Buffer overflow!
⚠️ Pitfall Guide:
-
strcpy does not check the size of the destination array! If src is longer than dest, it directly causes memory overflow!
-
Safe alternative: strncpy (but still has pitfalls!)
char dest[5];
strncpy(dest, "Hello, World!", sizeof(dest)); // Will not overflow, but may not have '\0'!
dest[sizeof(dest) - 1] = '\0'; // Manually add '\0'
-
Best practice: Use snprintf (C99)
snprintf(dest, sizeof(dest), "%s", "Hello, World!"); // Automatically truncates + '\0'
strcat(): String concatenation, beware of “memory stomping”
Function: Appends src to the end of dest.
Example:
char dest[10] = "Hello";
strcat(dest, "!"); // Correct → "Hello!"
strcat(dest, ", World!"); // Buffer overflow!
⚠️ Pitfall Guide:
-
strcat also does not check the remaining space in the destination array!
-
Safe alternative: strncat
char dest[10] = "Hello";
strncat(dest, ", World!", sizeof(dest) - strlen(dest) - 1); // Leave 1 byte for '\0'
Best practice: Calculate space in advance
if (strlen(dest) + strlen(src) + 1 <= sizeof(dest)) {
strcat(dest, src); // Safe
}
strcmp(): String comparison
Function: Compares two strings for equality.
Return values:
-
0: equal
-
<0: str1 < str2 (in lexicographical order)
-
>0: str1 > str2
if (strcmp("Hello", "Hello") == 0) {
printf("Same!\n");
}
if (strcmp("Apple", "Banana") < 0) {
printf("Apple comes before Banana!\n");
}
strstr(): String search
Function: Finds needle (substring) in haystack.
Example:
char *pos = strstr("Hello, World!", "World");
if (pos != NULL) {
printf("Found substring! Position: %s\n", pos); // Outputs "World!"
}
⚠️ Pitfall Guide:
-
If not found, returns NULL, do not dereference directly!
char *result = strstr(“Hello”, “Bye”);
printf(“%s\n”, result); // If result == NULL, crash!
-
To find all matches? Use a loop:
char text[] = "ababab";
char *p = text;
while ((p = strstr(p, "ab")) != NULL) {
printf("Found at: %ld\n", p - text);
p++; // Continue searching
}
strchr() & strrchr(): Character search
Function:
-
strchr(str, ch) → Finds character ch in str from left to right
-
strrchr(str, ch) → Finds character ch in str from right to left
Example: Find file extension
char filename[] = "image.png";
char *dot = strrchr(filename, '.'); // Find the last '.' from the right
if (dot != NULL) {
printf("Extension: %s\n", dot + 1); // Outputs "png"
}
⚠️ Pitfall Guide:
-
Returns NULL if not found, dereferencing directly will crash!
memcpy() & memmove(): Memory operations
Function: Copies memory blocks (lower level than strcpy, ignores ‘\0’).
|
Function |
Characteristics |
|
memcpy(dest, src, n) |
Fast, but src and dest memory must not overlap |
|
memmove(dest, src, n) |
Slow, but allows memory overlap |
int arr[] = {1, 2, 3, 4, 5};
memmove(arr + 1, arr, 4 * sizeof(int)); // Shift right by 1
// Result: {1, 1, 2, 3, 4} (last one is overwritten)
⚠️ Pitfall Guide:
-
memcpy with overlapping memory = undefined behavior (may crash or corrupt data)
-
When calculating byte size, use sizeof: memcpy(dest, src, sizeof(src))
memset(): The “painter” of memory filling
Function: Fills a memory block with a specified value.
Example: Initialize an array
char buffer[100];
memset(buffer, 0, sizeof(buffer)); // Fill all with 0 (similar to '\0')
memset(buffer, 'A', 10); // Fill first 10 bytes with 'A'
⚠️ Pitfall Guide:
-
Can only fill single-byte values
int nums[10];
memset(nums, 1, sizeof(nums)); // Each int will be set to 0x01010101 (not 1!)
sprintf() & snprintf(): The “magician” of formatting
Function: Formats a string into a character array (similar to printf, but outputs to memory).
|
Function |
Safety Level |
|
sprintf(buf, fmt, …) |
⚠️ Dangerous (does not check buffer size) |
|
snprintf(buf, size, fmt, …) |
✅ Safe (automatically truncates) |
⚠️ Pitfall Guide:
-
sprintf is a hotspot for buffer overflow! Always use snprintf
-
The return value is the “theoretical length” (excluding ‘\0’), which may be greater than the actual written length
|
Scenario |
Return Value |
Actual Written Buffer |
Buffer Content |
Explanation |
|
Buffer is large enough |
5 |
5 |
“Hello” |
Return value = actual written |
|
Buffer is too small |
5 |
3 |
“Hel” |
Return value > actual written (truncated) |
How snprintf() works
1) snprintf performs internal calculations
-
First simulates writing to an infinitely large buffer, calculating the total length of the string (e.g., “Hello, World!” → 13).
-
If the buffer is sufficient (size > ret), it writes the entire string + ‘\0’.
-
If the buffer is insufficient (size <= ret), it writes only the first size-1 characters + ‘\0’ (ensuring no overflow).
2) Return value rules
-
Always returns the theoretical length (not affected by buffer size limitations).
-
Actual written length = min(theoretical length, buffer size – 1).
strtok(): The “Swiss Army Knife” of string splitting
Function: Splits a string using delimiters (like commas, spaces).
Example: Parsing CSV data
char data[] = "Apple,Orange,Banana";
char *token = strtok(data, ","); // First call
while (token != NULL) {
printf("Fruit: %s\n", token);
token = strtok(NULL, ","); // Subsequent calls pass NULL
}
⚠️ Pitfall Guide:
-
Will modify the original string (replacing delimiters with ‘\0’), back up with strcpy if necessary
-
Be careful with consecutive delimiters: “A,,B” will skip empty fields

If you find the article useful, click “Share“, “Like“, “View“!