Absolutely not. Contrary to Microsoft's marketing campaign for their non-standard functions, strcpy
is safe when used properly.
The above is redundant, but mostly safe. The only potential issue is that you're not checking the malloc
return value, so you may be dereferencing null (as pointed out by kotlinski). In practice, this likely to cause an immediate SIGSEGV and program termination.
An improper and dangerous use would be:
char array[100];
// ... Read line into uncheckedInput
// Extract substring without checking length
strcpy(array, uncheckedInput + 10);
This is unsafe because the strcpy may overflow, causing undefined behavior. In practice, this is likely to overwrite other local variables (itself a major security breach). One of these may be the return address. Through a return to lib C attack, the attacker may be able to use C functions like system
to execute arbitrary programs. There are other possible consequences to overflows.
However, gets
is indeed inherently unsafe, and will be removed from the next version of C (C1X). There is simply no way to ensure the input won't overflow (causing the same consequences given above). Some people would argue it's safe when used with a known input file, but there's really no reason to ever use it. POSIX's getline
is a far better alternative.
Also, the length of str1
doesn't vary by compiler. It should always be 17, including the terminating NUL.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…