Char * src = new char [10];
Memset (SRC, 1, 10 );
Char * DEST = new char [20];
Strcpy (DEST, Src );
In this example, we cannot easily find a bug in the strcpy statement. Because SRC does not have a break.
Currently, the company uses codescan to find strcpy and use strncpy instead. But in fact, this method is not safe. Strcpy is uneasy because of the bug of the interface itself. strncpy can avoid strcpy's defects to some extent. However, strncpy is not secure. Because the number of bytes of the target pointer may be insufficient to store the content pointed to by the source pointer.
For example:
Char * src = "Hello world! ";
Char * DEST = new char [10];
Strncpy (DEST, SRC, strlen (SRC); // there is a bug
Currently, for strcpy and strncpy, the corresponding security version has been released since vs2005:
The interface definition is changed as follows:
Char * strcpy (char * DEST, const char * SRC) --> errno_t strcpy_s (char * DEST,
Size_t numelems, const char * SRC)
Char * strcpy (char * DEST, const char * SRC, size_t count) --> errno_t
Strcpy_s (char * DEST, size_t numelems, const char * SRC, size_t count)
The latter is safer than the former because they added a numelems parameter to the interface to indicate the number of bytes in the dest, preventing the bug caused by insufficient space in the target pointer DEST, and changing the return value to a return error.CodeInstead of returning char * for some convenience *. In this way, the interface definition is much safer than the original one.
So we should change strcpy to strncpy_s. This makes it safer.
Summary:
Interface Definition is often very important. But there are also some corresponding specifications. For example:
1) in the interface, if the target pointer to be modified appears, you need to increase the number of bytes that can be stored.
2) the interface generally returns int (errno_t is actually INT), which can mark the returned error type. (Note: In an abnormal environment, it is not returned. In some special cases, the desired type is directly returned .)