Memory leaks occur only in heap memory; they do not happen in stack memory. This is because stack memory automatically releases space after it has been allocated.What is heap memory? How is it stored?
First, let’s introduce how heap memory is stored inC code. The function used to dynamically allocate heap memory inC code ismalloc, and a common memory allocation code is shown in the figure below:
Since the return value of themalloc function is a memory address, the variable that stores heap memory must be a pointer. This variable can be a single pointer or a multiple pointer.How to obtain heap memory?There are two methods for obtaining heap memory: the first is to pass the memory pointer through the return value, and the second is to pass the memory pointer as a parameter.The use ofmalloc to allocate memory is a specific implementation of method one, which directly passes the return value to the memory pointer.Method one:Directly assign the function return value to the pointer, generally represented as follows:
Method two:Pass the pointer address as a function return parameter to save the heap memory address, generally represented as follows:
Summary:The essence of these two methods is the same; both involve indirect memory allocation within the function. However, the method of passing memory differs: method one passes the memory pointer through the return value, while method two passes the memory pointer through parameters.Three Causes of Memory Leaks
When our code experiences memory leaks, it generally includes the following causes:
-
Local pointer variables are defined within the function.
-
Memory allocation operations are performed on that local pointer.
-
The memory is not released before the function returns, nor is it saved to other global variables or returned to the previous function.
How to Check for Memory LeaksTo avoid memory leaks, we should develop good coding habits. When checking for memory leak issues, we generally need to do the following three things:
-
When we see local pointers in a function, we must carefully check for potential memory leaks and develop a habit of thorough checking.
-
If there are local variables and operations assigning values to local variables, we need to check what the returned pointer from the function points to: is it a global variable, static data, or heap memory? If there are unfamiliar interfaces in the code, we should find the corresponding interface documentation or analyze the source code to ensure that unnecessary errors do not occur.
-
If the function has memory allocation operations on local pointers, we need to check whether the saved data is a global variable or will be returned as a function return value. If neither is the case, we should check all the “return” statements in the function to ensure that memory is correctly released and does not occupy memory.