Why strcpy_s is safer than strcpy?

前端 未结 3 1765
天涯浪人
天涯浪人 2021-01-28 15:15

When I am trying to use the strcpy function the visual studio gives me an error

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


        
3条回答
  •  北海茫月
    2021-01-28 15:34

    strcpy_s needs the size of the destination, which is smaller than the source in your example.

    strcpy_s(b, sizeof(b), a);
    

    would be the way to go.

    As for the safety concept, there are many checks now done, and better ways to handle errors.

    In your example, had you used strcpy, you would have triggered a buffer overflow. Other functions, like strncpy or strlcpy, would have copied the 3 first characters without any null-byte terminator, which in turn would have triggered a buffer overflow (in reading, this time).

提交回复
热议问题