Programming Tips - C/C++: Function gets() isn't safe - here's a replacement

Date: 2000jun14 Update: 2026sep28 Language: C/C++ Q. C/C++: Function gets() isn't safe - here's a replacement A. Instead of:
char buf[1000]; gets(buf); // No bounds checking
Use fgets() like this:
char buf[1000]; fgets(buf, sizeof(buf), stdin); // fgets() checks for size
Full Example Use:
#include <stdio.h> int main() { char buf[5]; // Very small buffer for this demo, usuaully you would use 1K or 5K fgets(buf, sizeof(buf), stdin); // Check for size printf("buf=%s<\n", buf); }
Testing:
echo 1234567890 | ./tst
Output:
buf=1234<
The input was correctly truncated and a NUL inserted