Safe functions
- C course
- Expert
- Lesson 23/47
- 5 min
Learn safe alternatives like fgets instead of gets.
Safe functions
The C standard library offers safe alternatives: fgets instead of gets, strncpy instead of strcpy. These functions take an explicit size parameter.
fgets(buf, size, stdin) reads at most size - 1 bytes and null-terminates. strncpy(dst, src, n) copies at most n bytes; if the source is shorter it pads the destination with nulls, but if longer it does not write a terminator. So after strncpy it is safe to write dst[n-1] = '\0' manually. snprintf is the safe version of sprintf; it prevents overflow.
fgets and strncpy signatures
The signature of fgets is char *fgets(char *s, int size, FILE *stream). The size parameter sets the maximum number of bytes read; the function adds a null automatically.
The signature of strncpy is char *strncpy(char *dst, const char *src, size_t n). n is the maximum number of bytes to copy. If the source is longer than n, the destination is not null-terminated; the programmer must terminate it manually. Using sizeof(buf) safely provides the array size. Compiler warnings support these functions; gets was fully removed from modern C.
Practice Copy safely with strncpy
Add the <string.h> header. In main declare char dst1[8] and char dst2[4]. Call strncpy(dst1, "hello", 7) and set dst1[7] = '\0'; call strncpy(dst2, "world", 3) and set dst2[3] = '\0'. Print each with printf("%s\n", dst1) and printf("%s\n", dst2).
Starter code
#include <stdio.h>
// Add string.h header
// Use strncpy to copy into dst1 and dst2, null-terminate
// Print with printf
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <string.h>
int main(void) {
char dst1[8];
char dst2[4];
strncpy(dst1, "hello", 7);
dst1[7] = '\0';
strncpy(dst2, "world", 3);
dst2[3] = '\0';
printf("%s\n", dst1);
printf("%s\n", dst2);
return 0;
}Expected output
hello wor
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match safe and unsafe functions
| Term | Meaning |
|---|---|
gets |
Unsafe read |
fgets |
Safe read |
strcpy |
Unsafe copy |
strncpy |
Safe copy |
2 Which is a safe string reading function?
- scanf
- gets
- fgets Correct answer
- strcpy
Explanation: fgets takes a size parameter and prevents overflow.
3 Complete the fgets call
fgets(buf, sizeof(buf), ____);
fgets(buf, sizeof(buf), stdin);
Explanation: stdin is the standard input stream.