Strings and the standard library
Work with null-terminated character arrays and the safe string functions from the standard library.
- Read a string as a null-terminated char array.
- Measure a string with strlen and copy one with strcpy.
- Format into a fixed buffer with snprintf.
- Explain why gets is unsafe and what to use instead.
In plain English
A C string is a sequence of characters stored in a char array. The null terminator is a special character with the value zero that marks where the string ends, and every string function relies on it. The standard library is the set of ready-made functions that ship with C; strlen returns the length of a string, strcpy copies one string into another, and snprintf writes formatted text into a buffer without overflowing it. The old function gets reads input with no size limit, so a long line can write past the end of the array and corrupt memory, which is why it is unsafe and should never be used.
Step by step
- 1Declare a char array and initialise it with a string literal.
- 2Print the string and its length using strlen.
- 3Copy it into a second array with strcpy.
- 4Build a longer message with snprintf and a size.
- 5Look up why gets has no size argument and is therefore unsafe.
#include <stdio.h>
#include <string.h>
int main(void) {
char title[32] = "C Programming";
printf("length = %zu\n", strlen(title));
char copy[32];
strcpy(copy, title);
printf("copy = %s\n", copy);
char buffer[64];
snprintf(buffer, sizeof buffer, "%s has %d lessons", title, 5);
printf("%s\n", buffer);
return 0;
}Common mistakes
- Forgetting to leave room for the null terminator makes a buffer one byte too small for its string.
- Using strcpy into a destination that is too small overwrites whatever happens to sit next to it in memory.
- Calling strlen on a char array that has no null terminator reads past the end of the array.
- Using gets at all is a mistake, because it cannot stop a long line from overflowing the buffer.
Measure and copy a title
Declare a string title, print its length with strlen, copy it into a second buffer with strcpy, and print the copy.
char title[32] = "C Programming";
printf("length = %zu\n", strlen(title));Which function writes formatted text into a buffer but never past its size?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.