Why not disable the dangerous memcpy or update the memcpy source and use the safer memcpy_s

Regarding the question of using the safer memcpy_s without disabling the dangerous memcpy or updating the memcpy source, here are some considerations:

First, memcpy_s is not an absolutely safe implementation. Although it requires you to provide a length parameter to ensure that no overflow or out-of-bounds problems occur, this length still needs to be provided by yourself, rather than judged by various black magic of the standard library. These so-called "safe functions" can still silently raise errors if you pass in a wrong length, just like the non-safe versions. Also, you probably don't always check for errors that are returned, especially if you're sure the target location is large enough, which is one of the root causes of out-of-bounds accesses in many programs.

Second, in many situations that require a large amount of data copying, especially when IO operations are involved, frequent length judgments can seriously affect performance, especially when the data length is different each time. This can lead to massive errors in branch predictions, severely degrading performance. It just so happens that I have an embedded learning route here, and I need to leave a 6 for various projects.

Finally, there is the issue of portability. Currently only the Windows platform enforces the use of such security functions, while on other platforms, such security functions are not required for the C runtime library. If you write code that needs to use these functions, someone else is still using an older version of the GCC 3.3 compiler, which will probably tell you that the code won't compile. This requires you to make a distinction when writing code to write code that accommodates both situations.

In summary, considering that the security of memcpy_s is not absolute, performance loss, and portability issues, it is necessary to weigh the pros and cons and make decisions based on specific situations in terms of whether to disable dangerous memcpy or update memcpy source code.


ab9c7eb24455d80ed5baa99bc75b6543.jpeg

d358f084b6ae60325b62c03735c67252.jpeg

Guess you like

Origin blog.csdn.net/linlaoshi2009/article/details/132237451