C11
& C++14
standards have dropped gets()
function that is inherently insecure & leads to security problems because it doesn't performs bounds checking results in buffer overflow. Then why C11
standard doesn't drop strcat()
& strcpy()
functions? strcat()
function doesn't check to see whether second string will fit in the 1st array. strcpy()
function also contains no provision for checking boundary of target array. What if the source array has more characters than destination array can hold? Most probably program will crash at runtime.
So, wouldn't it be nice if these two unsafe functions completely removed from the language? Why they are still exist? What is the reason? Wouldn't it is fine to have only functions like strncat(),strncpy()
? If I am not wrong Microsoft C & C++ compiler provides safe versions of these functions strcpy_s(),strcat_s()
. Then why they aren't officially implemented by other C compilers to provide safety?
gets()
is inherently unsafe, because in general it can overflow the target if too much data is received onstdin
. This:will cause undefined behavior if more than
MANY
characters are entered, and there is typically nothing the program can do to prevent it.strcpy()
andstrcat()
can be used completely safely, since they can overflow the target only if the source string is too long to be contained in the target array. The source string is contained in an array object that is under the control of the program itself, not of any external input. For example, this:cannot possibly overflow unless the program itself is modified.
strncat()
can be used as a safer version ofstrcat()
-- as long as you specify the third argument correctly. One problem withstrncat()
is that it only gives you one way of handling the case where there's not enough room in the target array: it silently truncates the string. Sometimes that might be what you want, but sometimes you might want to detect the overflow and do something about it.As for
strncpy()
, it is not simply a safer version ofstrcpy()
. It's not inherently dangerous, but if you're not very careful you can easily leave the target array without a terminating'\0'
null character, leading to undefined behavior next time you pass it to a function expecting a pointer to a string. As it happens, I've written about this.