Why should you use strncpy instead of strcpy?

后端 未结 10 1062

Edit: I\'ve added the source for the example.

I came across this example:

char source[MAX] = \"123456789\";
char source1[MAX] = \"12         


        
10条回答
  •  长发绾君心
    2020-11-22 06:39

    While I know the intent behind strncpy, it is not really a good function. Avoid both. Raymond Chen explains.

    Personally, my conclusion is simply to avoid strncpy and all its friends if you are dealing with null-terminated strings. Despite the "str" in the name, these functions do not produce null-terminated strings. They convert a null-terminated string into a raw character buffer. Using them where a null-terminated string is expected as the second buffer is plain wrong. Not only do you fail to get proper null termination if the source is too long, but if the source is short you get unnecessary null padding.

    See also Why is strncpy insecure?

提交回复
热议问题