C strcpy() - evil?

前端 未结 17 1398
梦毁少年i
梦毁少年i 2020-12-23 10:50

Some people seem to think that C\'s strcpy() function is bad or evil. While I admit that it\'s usually better to use strncpy() in order to avoid bu

17条回答
  •  遥遥无期
    2020-12-23 11:09

    The evil comes when people use it like this (although the below is super simplified):

    void BadFunction(char *input)
    {
        char buffer[1024]; //surely this will **always** be enough
    
        strcpy(buffer, input);
    
        ...
    }
    

    Which is a situation that happens suprising often.

    But yeah, strcpy is as good as strncpy in any situation where you are allocating memory for the destination buffer and have already used strlen to find the length.

提交回复
热议问题