← GCC/C Index

🔤 <string.h> — String & Memory Operations

Functions for manipulating C-style null-terminated strings and raw memory blocks. Always ensure destination buffers are large enough to avoid buffer-overflow vulnerabilities.

Include: #include <string.h> | Compile: gcc -Wall -o prog prog.c

📋 Functions & Macros

NamePrototype / ValueDescription
strlensize_t strlen(const char *s)Length of string (not counting '\0')
strcpychar *strcpy(char *dst, const char *src)Copy src into dst (unsafe — prefer strncpy)
strncpychar *strncpy(char *dst, const char *src, size_t n)Copy at most n chars from src to dst
strcatchar *strcat(char *dst, const char *src)Append src to end of dst
strncatchar *strncat(char *dst, const char *src, size_t n)Append at most n chars of src to dst
strcmpint strcmp(const char *a, const char *b)Compare strings; 0 = equal
strncmpint strncmp(const char *a, const char *b, size_t n)Compare at most n chars
strchrchar *strchr(const char *s, int c)Find first occurrence of char c in s
strrchrchar *strrchr(const char *s, int c)Find last occurrence of char c in s
strstrchar *strstr(const char *hay, const char *needle)Find first occurrence of substring
strtokchar *strtok(char *s, const char *delim)Split string by delimiter tokens
strtok_rchar *strtok_r(char *s, const char *delim, char **save)Thread-safe strtok
memcpyvoid *memcpy(void *dst, const void *src, size_t n)Copy n bytes (no overlap)
memmovevoid *memmove(void *dst, const void *src, size_t n)Copy n bytes (handles overlap)
memsetvoid *memset(void *s, int c, size_t n)Fill n bytes with value c
memcmpint memcmp(const void *a, const void *b, size_t n)Compare n bytes of memory
memchrvoid *memchr(const void *s, int c, size_t n)Find first byte c in n bytes
strdupchar *strdup(const char *s)Duplicate string (malloc'd — caller must free)
strerrorchar *strerror(int errnum)Return error description string

💡 Example Program

Copy, save as demo.c, and compile with the command shown at the bottom.

#include <stdio.h>
#include <string.h>

int main(void) {
    char src[] = "Hello, World!";
    char dst[64];

    strncpy(dst, src, sizeof(dst) - 1);
    dst[sizeof(dst) - 1] = '\0';
    printf("dst    = \"%s\"\n", dst);
    printf("length = %zu\n", strlen(dst));

    char *p = strstr(dst, "World");
    if (p) printf("Found at index %td\n", p - dst);

    char csv[] = "apple,banana,cherry";
    char *tok = strtok(csv, ",");
    while (tok) { printf("token: %s\n", tok); tok = strtok(NULL, ","); }

    char buf[16];
    memset(buf, 'A', sizeof(buf) - 1);
    buf[sizeof(buf) - 1] = '\0';
    printf("buf    = %s\n", buf);
    return 0;
}
/* Compile: gcc -Wall -o str_demo str_demo.c */

← <math.h>  |  🏠 Index  |  <stdlib.h> →