Is the function strcpy always dangerous?

后端 未结 9 2374
不知归路
不知归路 2020-12-06 08:22

Are functions like strcpy, gets, etc. always dangerous? What if I write a code like this:

int main(void)
{

char *str1 = \"abcdefghijklmnop\";
char *str2 = m         


        
9条回答
  •  日久生厌
    2020-12-06 08:56

    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.

提交回复
热议问题