1.strcpy ()
The strcpy () function copies the source string to a buffer. The exact number of characters to copy is not specified. The number of characters copied directly depends on the number in the source string. If the source string happens to come from user input and does not specifically limit its size, it is possible to get into big trouble! It is recommended to use strncpy ().
2.strcat ()
The strcat () function is very similar to strcpy (), except that it can merge a string into the end of the buffer. It also has a similar, safer alternative to strncat (). If possible, use Strncat () instead of strcat ().
3. Gets
- void Main ()
- {
- Char buffer[5];
- /* DON ' T do this */
- while ((buffer[i++] = GetChar ())! = ' \ n ')
- {
- };
- }
Recommended use of Fgets
4.sprintf () vsprintf ()
The functions sprintf () and vsprintf () are common functions used to format text and buffer it. They can mimic the strcpy () behavior in a direct manner. In other words, using sprintf () and vsprintf () is as easy as using strcpy () to cause a buffer overflow to the program.
5.SCANF () series
scanf () sscanf () fscanf () vfscanf () vscanf () vsscanf ()
The functions of the SCANF series are also poorly designed. In this case, the destination buffer will overflow. Consider the following code:
- void Main (int argc, char **argv)
- {
- Char buf[256];
- SSCANF (Argv[0], "%s", &buf);
- }
If the input word is greater than the size of the BUF, there is an overflow condition.
There are several other situations:
A) The use of "%x" or "%d", but the last parameter is char, can also cause overflow, because "%x" or "%d" is read 4 bytes, Char has only one byte, so it is possible to overwrite the later content.
b) reading a 64-bit number using "d%" may also cause overflow
c) When using the bool type defined for int, overflow occurs when the value is assigned to a char type
6. StrDup ()
The StrDup () function is a string that copies the input string and returns the new request memory. It is called malloc, so after calling StrDup, free is required to release the requested memory.
- #include
- #include
- void Main (void)
- {
- char buffer[] = "This is the buffer text";
- Char *newstring;
- printf ("Original:%s\n", buffer);
- newstring = strdup (buffer);
- Free (newstring);
- }
A function that is prone to memory overflow in C + +