Skip to content
  • string.h Functions · C

string.h Functions

LearnViaNotes @learnvianotes· 3 min read

<string.h> provides string (str…) and raw memory (mem…) functions. None of them allocate memory or check destination sizes — you supply buffers big enough.

FunctionDoesNotes
strlen(s)Length excluding \0O(n)
strcpy(d, s) / strncpy(d, s, n)Copystrcpy overflows if d is too small; strncpy may not NUL-terminate
strcat(d, s) / strncat(d, s, n)Appendstrncat always terminates; n = max chars to append
strcmp(a, b) / strncmpCompare<0, 0, >0 — not just −1/0/1
strchr(s, c) / strrchrFirst / last occurrence of a charReturns pointer or NULL
strstr(h, n)Find substringPointer or NULL
strspn / strcspnLength of prefix made of / not made of a sets[strcspn(s, "\n")] = 0 strips a newline
strtok(s, delims)Split into tokensModifies s, keeps hidden static state — not reentrant
memcpy(d, s, n)Copy n bytesRegions must not overlap
memmove(d, s, n)Copy n bytesOverlap-safe
memset(p, byte, n)Fill bytesSets bytes, not ints
memcmp(a, b, n)Compare bytesDon’t use on structs (padding bytes)

Copy, concatenate, compare

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

int main(void) {
    char buf[32];
    strcpy(buf, "Hello");
    strcat(buf, ", ");
    strncat(buf, "world!!!", 6);          /* append at most 6 chars */
    printf("%s (%zu)\n", buf, strlen(buf));

    printf("%d %d %d\n", strcmp("apple", "apple") == 0,
           strcmp("apple", "banana") < 0, strcmp("b", "a") > 0);
    printf("%d\n", strncmp("prefix-match", "prefix-other", 6) == 0);
    return 0;
}
Output
Hello, world! (13)
1 1 1
1

Searching

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

int main(void) {
    const char *path = "/usr/local/bin/gcc";
    const char *slash = strrchr(path, '/');
    printf("file: %s\n", slash + 1);
    printf("dir length: %td\n", slash - path);

    const char *hit = strstr(path, "local");
    printf("found \"local\" at index %td\n", hit - path);
    printf("%s\n", strchr(path, 'z') == NULL ? "no z" : "has z");
    printf("vowel-free prefix of \"strength\": %zu\n", strcspn("strength", "aeiou"));
    return 0;
}
Output
file: gcc
dir length: 14
found "local" at index 5
no z
vowel-free prefix of "strength": 3

Tokenising with strtok

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

int main(void) {
    char csv[] = "name,,age;city";              /* must be writable */
    for (char *tok = strtok(csv, ",;"); tok; tok = strtok(NULL, ",;"))
        printf("[%s] ", tok);                    /* empty fields are skipped */
    printf("\n");
    return 0;
}
Output
[name] [age] [city]

Memory functions

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

int main(void) {
    int a[5] = {1, 2, 3, 4, 5}, b[5];
    memcpy(b, a, sizeof a);                  /* copy the whole array */

    memmove(a + 1, a, 3 * sizeof a[0]);      /* overlapping shift right */
    for (int i = 0; i < 5; i++) printf("%d ", a[i]);
    printf("\n");

    memset(b, 0, sizeof b);                  /* zero is safe for any type */
    printf("%d %d\n", b[0], b[4]);

    int ones[2];
    memset(ones, 1, sizeof ones);            /* sets BYTES to 1: 0x01010101 */
    printf("%d\n", ones[0]);
    return 0;
}
Output
1 1 2 3 5
0 0
16843009

Buffer overflow with strcpy

C — stack-buffer-overflow caught by AddressSanitizer
#include <stdio.h>
#include <string.h>

int main(void) {
    char small[8];
    const char *input = "this is far too long";
    strcpy(small, input);          /* writes 21 bytes into 8 */
    printf("%s\n", small);
    return 0;
}
C — the safe version
#include <stdio.h>
#include <string.h>

int main(void) {
    char small[8];
    const char *input = "this is far too long";
    snprintf(small, sizeof small, "%s", input);   /* truncates, always terminates */
    printf("%s\n", small);
    return 0;
}
Output
this is

What is the difference between memcpy and memmove?

Why is strtok considered unsafe?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report