Difference between 'strcpy' and 'strcpy_s'?

前端 未结 2 1642
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 09:45

When i tries to use strcpy to copy a string it gave me a compile error.

error C4996 \'strcpy\': This function or variable may be unsafe.
         


        
2条回答
  •  情歌与酒
    2020-11-30 10:31

    strcpy is a unsafe funtion. When you try to copy a string using strcpy(), to a buffer which is not large enough to contain it, it will cause a buffer overflow.

    strcpy_s() is a security enhanced version of strcpy(). With strcpy_s you can specify the size of the destination buffer to avoid buffer overflows during copies.

    char tuna[5];  // a buffer which holds 5 chars incluing the null character.
    char salmon[] = "A string which is longer than 5 chars";
    
    strcpy( tuna, salmon ); // This will corrupt your memory because of the buffer overflow.
    
    strcpy_s( tuna, 5, salmon ); // strcpy_s will not write more than 5 chars.
    

提交回复
热议问题