Is the function strcpy always dangerous?

后端 未结 9 2389
不知归路
不知归路 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:40

    yes, it is dangerous. After 5 years of maintenance, your code will look like this:

    int main(void)
    {
    
    char *str1 = "abcdefghijklmnop";
    
    {enough lines have been inserted here so as to not have str1 and str2 nice and close to each other on the screen}
    
    char *str2 = malloc(100); 
    strcpy(str2, str1);
    
    
    }
    

    at that point, someone will go and change str1 to

    str1 = "THIS IS A REALLY LONG STRING WHICH WILL NOW OVERRUN ANY BUFFER BEING USED TO COPY IT INTO UNLESS PRECAUTIONS ARE TAKEN TO RANGE CHECK THE LIMITS OF THE STRING. AND FEW PEOPLE REMEMBER TO DO THAT WHEN BUGFIXING A PROBLEM IN A 5 YEAR OLD BUGGY PROGRAM"

    and forget to look where str1 is used and then random errors will start happening...

提交回复
热议问题