Skip to content
CurriculumChapter 15 ยท Arrays & Strings
IntermediateHigh focus~14 min

String Library & Safe Input

The string library is small, fast, and trusting. Every function assumes you have already made room for the result.

In plain English

The string library gives you tools, but none of them check whether the box is big enough.

01

strlen, strcpy, strcat, and strcmp

strlen returns the number of characters before the terminator. strcpy copies a source string into a destination; strcat appends a source to a destination; strcmp compares two strings lexicographically and returns zero when they are equal. None of these functions knows the destination capacity, so the caller must guarantee enough space.

chapter-15.cC
char name[32] = "Ada";
char full[64];

strcpy(full, name);
strcat(full, " Lovelace");
printf("%s\n", full);              /* Ada Lovelace */
printf("%d\n", strcmp(name, "Ada")); /* 0 */
02

Safe input and termination bugs

gets() cannot know the buffer size and was removed from modern C. fgets(buffer, size, stdin) reads at most size - 1 characters and always terminates the buffer. Remember that fgets keeps the newline if it fits, so you may need to strip it. A missing terminator turns a string into a buffer overrun waiting to happen.

chapter-15.cC
char line[32];
if (fgets(line, sizeof line, stdin)) {
    size_t n = strlen(line);
    if (n > 0 && line[n - 1] == '\n') line[n - 1] = '\0';
    printf("read: %s\n", line);
}

Key takeaways

  • strlen counts before the terminator.
  • strcpy and strcat do not check destination capacity.
  • strcmp returns 0 for equal strings.
  • Use fgets instead of gets.

Common pitfalls

  • Using strcpy into a buffer that is too small.
  • Comparing strings with == instead of strcmp.
  • Forgetting that fgets keeps the newline.

Key focus

  • Trace strcpy/strcat buffer contents.
  • Know the return convention of strcmp.

Quick check

0 / 2 answered

1. What does strcmp("apple", "apple") return?

2. Which function safely copies a string into a sized buffer?