C - String Manipulation
C strings are null-terminated arrays of char
. Use string.h
functions carefully to avoid overflows.
Learning Objectives
- Use
strlen
,strcpy
/strncpy
,strcat
/strncat
,strcmp
. - Allocate enough space and include the terminating null.
Examples
#include <stdio.h>
#include <string.h>
int main(void) {
char dst[16] = "Hello";
const char *src = "World";
strcat(dst, " "); // dst = "Hello "
strncat(dst, src, 5); // dst = "Hello World"
printf("%s (%zu)\n", dst, strlen(dst));
}
Common Pitfalls
- Buffer overflows when destination is too small.
- Using
strcpy
/strcat
unsafely; prefer length-bounded variants when possible.