I. Preface
When developing products using C language, the flexibility of pointer operations in C language also requires special attention when using pointers. A little less rigorous will cause memory problems, such as memory not initialized, memory leakage and repeated memory release. However, in actual development, the use of pointers is inevitable, so memory problems are inevitable, because it is impossible for everyone to carefullyCodeAnd review the Code. If these problems occur, what can be done? In this case, it is necessary to use the memory detection module during project development.
Ii. Basic Principles
To use a new memory, either from the stack or from the stack, if it is from the stack, then record the requested memory start address and allocated size, the file name and row number (which row of the file calls the allocation function). If the memory on the stack is released, the released address is also recorded, the file name and row number (which row of the file calls the release function). This way, if you record all the allocation and release operations, you can solve some memory operation problems,
Such as memory leakage and repeated memory release. The general structure is shown in:
3. Application Development
In C language, the memory application function is malloc and the memory release function is free. If we directly use these two functions in product development, how can we get the file name and row number? Therefore, the malloc and free functions must be encapsulated,
Use macros for encapsulation, as shown in figure
# Define dawen_malloc (_ SIZE) my_malloc (_ SIZE ,__ file __,__ line __)
# Define dawen_free (_ pointer) my_free (_ pointer ,__ file __,__ line __)
The _ file __,__ line _ macro is the system-Defined Macro, which indicates the file name and row number of the current Code run. Then, use the malloc system function in the my_malloc function, use the free system in the my_free Function
Function to record some information. Therefore, during development, my_malloc is used to apply for memory and my_free is used to release memory.
Iv. Memory Operation considerations
I have written the pointer operation in C language development here and I hope to learn it with you:
1. After applying for a piece of memory, the memory should be initialized, such as callingReset memset
2. After applying for memory, the null value should be determined for the pointer after the application before the operation.
3. After the pointer is released, the pointer must be assigned null values. Of course, the value assignment operation is performed in the my_free function. Therefore, the parameter of the my_free function is a level-2 pointer.
4. Stick to the rule of who applies for release. If not, the members of the group should negotiate or add comments to the code.
V. Remarks
We have been unable to find a good method for detecting memory overwrite and out-of-memory access .. Depressed ..