How to troubleshoot memory leaks/memory safety

1. If there are not many codes and you are familiar with them. You can check the code directly (whether malloc, free, and newdelete are used in pairs, and the destructor does not use virtual functions? The resources of the parent process such as fd are not released during fork? Dangling pointers, etc.). You can also directly debug with gdb, step/breakpoint. You can know which step went wrong. For memory leaks, if a large memory leak is allocated at the beginning, an error message will be prompted directly.

2. Many codes are unfamiliar.
Use a detection tool such as varglind lea check -fully. It will tell you where it is definitely leaking, where it might be leaking, and where it is indirectly leaking. For the affirmative, it is good to modify it, and for the possible, the indirect one needs to be considered again.

3. coredump file
Some memory leaks lead to crashes that will generate core files, such as memory leaks leading to stack overflow. ulimit can check whether it is enabled and the size limit. It saves the state of the memory at that time, such as the value of the register, the stack pointer, the function call and other information.
The core file will tell you what kind of error (such as a memory leak) at the beginning. You can debug the core file with gdb. For example, call the bt command to view the function call stack frame information when an error occurs, and frame to view more specific information about a stack frame. Then break the point at the corresponding function position to see which step went wrong. There is an addr2line tool, which can convert the memory address information into the corresponding function name line number, which is more convenient for analysis;
(Other reasons for core exceptions such as: read and write out of bounds, division by zero exception, kill signal, multi-thread shared data structure No locks, illegal pointers, etc.)
4.
If it is not the first scene when reloading malloc, the possible error is not here at all, especially when using some other libraries. What kind of dynamic allocation is used at the bottom of these libraries? If we don't understand the mechanism, it is easy to leak memory. So you can overload malloc and free to write logs, for example, write how much memory is allocated by the xxx function, and free will do the opposite, so as to analyze where there is a leak.

Guess you like

Origin blog.csdn.net/weixin_53344209/article/details/131380982