For security reasons, use the C language realloc () function carefully
Http://www.360doc.com/content/16/0712/09/19227797_574892368.shtml
In C, good programming habits require a function to do only one thing, if a function implements a number of functions, it can be said that basically a bad design.
The C language ReAlloc () function is located in the Stdlib.h header file, and its prototype is:
void *realloc (void *ptr, size_t size);
ReAlloc () modifies the size of the memory block pointed to by PTR and returns the new memory pointer.
Before setting the size of the memory block to N, if size < N, then the intercepted content will not change, if size > N, then the newly allocated memory will not be initialized.
If ptr = NULL, then it is equivalent to calling malloc (size), or if size = 0, it is equivalent to calling free (PTR).
If PTR is not NULL, then he must have been returned by the previous memory allocation function, such as malloc (), calloc (), or realloc ().
If the block of memory referred to by PTR is moved, then free (PTR) is called.
See, a simple realloc () gives several functions, which is not a good function design. The estimate is also for compatibility, only to tolerate this function has been in the C library. Although ReAlloc () provides some convenience in coding, it is also easy to raise bugs.
Here are two examples to illustrate.
1) realloc () The first behavior caused by the bug
- void *ptr = ReAlloc (ptr, new_size);
- if (!ptr) {
- Error handling
- }
This leads to a memory leak problem, which returns NULL when the REALLOC () allocation fails. However, the memory of PTR in the parameter is not released. If the return value of ReAlloc () is assigned directly to PTR. Then, when the application memory fails, it will cause the memory that the PTR originally pointed to loses, causes the memory to be free and leaks.
The correct handling should be this:
- void *new_ptr = ReAlloc (ptr, new_size);
- if (!new_ptr) {
- Error handling.
- }
- PTR = New_ptr
2) The third behavior caused by the bug
In fact, malloc (0) is a legitimate statement that returns a valid pointer, which can be freed by free. This caused a lot of people to realloc () the misunderstanding, that when size is 0 o'clock, actually realloc () will return a valid pointer, still need to use free to release the memory.
- void *new_ptr = ReAlloc (old_ptr, new_size);
- Other code
- Free (NEW_PTR);
Because of the wrong understanding, do not test whether the new_size is 0, or according to new_size not 0 logic processing, and finally free (NEW_PTR). The problem of double free is introduced here, causing the program to crash.
So, realloc () This design and not very good function trap or a lot of, accidentally on the Thunder, the above is just two simple small examples, we should pay attention to some other small problems in the actual use.
Go: Be careful with the C language realloc () function for security reasons