String safety
- C course
- Intermediate
- Lesson 22/116
- 5 min
Learn safe string handling with strncpy and strncat.
Safe copying with strncpy
strncpy(dest, src, n) copies at most n bytes from src to dest. This prevents overflow but has a catch: if src is longer than n, dest isn't null-terminated.
Example: char dest[4]; strncpy(dest, "Merhaba", 4);. Here only "Merh" is copied (4 bytes), no null is added. For safe use you must terminate with dest[n-1] = '\0';. This pattern is standard for untrusted sources like user input and network data. Unlike strcpy, strncpy checks size.
Safe concatenation with strncat
strncat(dest, src, n) appends at most n bytes from src to the end of dest. Unlike strncpy, it always adds a null terminator.
Example: char dest[20] = "Merhaba"; strncat(dest, " dünya", 6);. Here at most 6 bytes are appended; the result is null-terminated. n is the maximum number of bytes to append; not the total size of dest. So computing n as sizeof(dest) - strlen(dest) - 1 is the safe pattern. strncat is the safe version of strcat.
Practice Safe copy with strncpy
Declare a four-byte array char dest[4];. Copy at most three bytes with strncpy(dest, "Merhaba", 3);. Null-terminate with dest[3] = '\0';. Print with printf("%s\n", dest);. Include <string.h>.
Starter code
#include <stdio.h>
#include <string.h>
// Declare dest[4]
// Copy 3 bytes with strncpy
// Null-terminate dest[3], print
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <string.h>
int main(void) {
char dest[4];
strncpy(dest, "Merhaba", 3);
dest[3] = '\0';
printf("%s\n", dest);
return 0;
}Expected output
Mer
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the safe functions
| Term | Meaning |
|---|---|
strncpy |
Bounded copy |
strncat |
Bounded append |
snprintf |
Bounded format |
strcpy |
Unbounded (unsafe) |
2 Complete the strncpy call
char dest[4];
____(dest, "Merhaba", 3);
dest[3] = '\0';
char dest[4];
strncpy(dest, "Merhaba", 3);
dest[3] = '\0';
Explanation: strncpy does bounded copying.
3 What does strncpy do?
- Copies without bound
- Only returns a pointer
- Returns the string length
- Copies at most n bytes Correct answer
Explanation: strncpy copies at most n bytes; this prevents overflow.