Memory leak detection method and device and computing equipment

By automatically generating parameterized test scripts using a neural network model and monitoring memory behavior in real time, the accuracy problem of existing memory leak detection methods is solved, achieving efficient and accurate memory leak location and detection.

CN121901007APending Publication Date: 2026-04-21XFUSION DIGITAL TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
XFUSION DIGITAL TECH CO LTD
Filing Date
2025-11-26
Publication Date
2026-04-21

AI Technical Summary

Technical Problem

Existing memory leak detection methods suffer from false negatives and false negatives, resulting in inaccurate detection results and failing to effectively improve system stability and performance.

Method used

The system uses a neural network model to automatically generate parameterized test scripts, monitors memory behavior in real time, and accurately locates the code where memory leaks occur by combining runtime data, generating a leak detection report.

Benefits of technology

It improves the accuracy and efficiency of memory leak detection, can quickly locate the root cause of memory leaks, reduce invalid testing overhead, and enhance the ability to detect hidden leak problems.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121901007A_ABST
    Figure CN121901007A_ABST
Patent Text Reader

Abstract

Embodiments of the invention provide a memory leak detection method and apparatus, and a computing device. The method comprises the steps of obtaining a to-be-tested code; taking the to-be-tested code as the input of the first neural network model, and generating a parameterized test script of the to-be-tested code by using the first neural network model; operating the parameterized test script; in the process of executing the parameterized test script, monitoring runtime data of the to-be-tested code; under the condition that the memory leaks, determining the position of a code causing the memory to leak in the to-be-tested code according to the runtime data; generating a leakage detection report; the leak detection report includes a code location and a test execution path. By adopting the method, the leak behavior of the to-be-tested code is verified by dynamically executing the parameterized test script, and the memory leak point is specifically positioned, so that the accuracy and comprehensiveness of detection can be effectively improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of software testing technology, and in particular to a method, apparatus and computing device for detecting memory leaks. Background Technology

[0002] In software development, code defects are one of the main causes of memory leaks. Memory leaks typically stem from improper resource management, such as failure to properly release file handles, unresolved circular references, or non-compliant use of third-party libraries. These problems lead to a continuous increase in memory usage during program runtime, thereby affecting system stability and performance. To ensure system reliability, it is crucial to build an efficient memory leak detection mechanism.

[0003] Currently, existing memory detection methods mainly rely on matching the code to be detected against a predefined rule base to generate a potential risk report, which is then manually analyzed by developers to determine whether remediation is needed. However, these memory detection methods are prone to false negatives and false negatives, leading to inaccurate results. Summary of the Invention

[0004] This application provides a method for detecting memory leaks. By using a neural network model to automatically generate parameterized test scripts and monitoring memory behavior during execution, the location of memory leaks can be obtained, which can effectively improve the accuracy of memory leak detection.

[0005] To achieve the above objectives, the embodiments of this application adopt the following technical solutions: In a first aspect, embodiments of this application provide a method for detecting memory leaks. The method includes obtaining code to be tested; using the code to be tested as input to a first neural network model, generating a parameterized test script for the code to be tested using the first neural network model; running the parameterized test script; monitoring runtime data of the code to be tested during the execution of the parameterized test script; determining the location of the code in the code to be tested that causes the memory leak based on the runtime data if a memory leak occurs; generating a leak detection report; the leak detection report includes the code location and the test execution path.

[0006] Based on this solution, after obtaining the code to be tested, a neural network model is used to understand the code and automatically generate parameterized test scripts with high coverage. During the dynamic execution of the scripts, the runtime data of the program is monitored in real time to detect memory leaks. When a leak is confirmed, the specific location of the leaking code is accurately located by combining the runtime data. This can effectively improve the accuracy of memory detection.

[0007] In one possible implementation, obtaining the code to be tested for memory leak detection includes: obtaining a first target code, which is any code segment in the source code; determining a second target code in the first target code that conforms to memory leak characteristics based on the first target code and a preset memory leak feature pattern; performing syntax parsing on the second target code to generate a first target structure tree for the second target code; the first target structure tree is used to reflect the syntactic structure relationship of the second target code; matching the first target structure tree with structured memory leak detection rules in a preset rule base to obtain the code to be tested; the code to be tested is a code segment in the first target code that has a potential memory leak risk.

[0008] Based on this scheme, the source code fragments (first target code) are initially screened by combining preset memory leak feature patterns to identify code parts with suspicious characteristics (second target code). Then, syntax parsing is performed to generate an abstract syntax tree (first target structure tree) representing its syntactic structure relationship. This structure tree is then matched with structured detection rules in a preset rule base to accurately extract high-risk code fragments that have both semantic suspicion and structural matching as the code to be tested. In this way, by performing multi-level screening of the source code, potential risky code that conforms to known leak patterns and has a matching syntactic structure is identified, reducing ineffective testing overhead and improving the efficiency and accuracy of overall memory detection.

[0009] In another possible implementation, in the event of a memory leak, the location of the code causing the memory leak in the code under test is determined based on runtime data. This includes: determining the third target code in the code under test based on the matching relationship between runtime data and preset exception judgment conditions; using the second target structure tree as input to the second neural network model, and using the second neural network model to obtain at least one code defect rule and at least one memory leak code location; wherein, the second target structure tree is used to characterize the structural relationship of the third target code.

[0010] Based on this solution, by combining runtime data with preset anomaly judgment conditions, a third target code suspected of leakage is initially identified. Its structural information is then input into a second neural network model in the form of a second target structure tree for deep semantic analysis to obtain the specific code location of the memory leak. In the case of confirmed memory leakage, the specific memory leak location, i.e. the code location, can be accurately deduced, which can help users quickly locate the root cause of the problem and improve the accuracy of leak point identification.

[0011] In another possible implementation, the third target code in the code under test is determined based on the matching relationship between runtime data and preset exception judgment conditions. This includes: obtaining at least two memory snapshots of the code under test during the execution of the parameterized test script; comparing and analyzing the at least two memory snapshots to obtain at least one target object type; determining the target object type as an exception object type if the number of instances or the total memory usage of the target object type shows a monotonically increasing trend between the two snapshots; and determining the third target code in the code under test based on the creation location and / or reference holding path of at least one exception object type.

[0012] Based on this approach, two memory snapshots are collected during the execution of the parameterized test script, and their comparative analysis identifies object types that show a continuous upward trend in the number of instances or memory usage over time, classifying them as anomalous object types. Further reverse tracing is performed by combining the creation point of these anomalous objects and their reference holding paths to determine the key code regions (third-party target code) related to the leak. This effectively identifies long-term cumulative memory leaks, enhances the detection capability for hidden leaks, and improves the comprehensiveness and accuracy of the detection.

[0013] In another possible implementation, before obtaining the code to be tested, the following steps are also included: obtaining multiple raw code features and corresponding repair methods for each raw code feature; the raw code features are used to characterize structured code fragments with preset memory leak feature patterns; the raw code features include a first type of code features and a second type of code features; the first type of code features are structured code features extracted based on known memory leak issues in open-source code repositories and vulnerability databases; the second type of code features are structured code patterns extracted from historical memory leak cases, which are determined based on runtime monitoring data; memory leak detection rules are generated based on the first type of code features, the second type of code features, and preset rule templates; and multiple memory leak detection rules and multiple repair methods are stored in a preset rule base.

[0014] Based on this solution, by integrating known leakage patterns (first-type code features) from open-source code repositories and vulnerability databases with historical leakage cases extracted from actual operational monitoring (second-type code features), a structured memory leak detection rule system that combines breadth and realism is constructed, and corresponding remediation methods are associated with it and pre-stored in the rule base. In this way, during subsequent detection, the system can quickly identify potentially risky code based on high-quality rules validated by multi-source data, while providing accurate remediation suggestions, effectively improving the comprehensiveness and accuracy of memory leak detection.

[0015] In another possible implementation, after generating the leak detection report, the method further includes: evaluating multiple code defect rules to obtain the evaluation results corresponding to each code defect rule; when the evaluation results meet the preset rule entry conditions, adding at least one of the multiple code defect rules as a memory leak detection rule to the preset rule library.

[0016] Based on this solution, multiple code defect rules discovered during the detection process are comprehensively evaluated. If the evaluation results meet the preset inclusion criteria, representative and universal rules are added to the preset rule base. This enables dynamic updates to the preset rule base, continuously improving its coverage for identifying new or variant memory leak patterns.

[0017] In another possible implementation, after generating the leak detection report, the process includes: constructing training samples based on the code location and its corresponding runtime data; and fine-tuning the first neural network model using the training samples to update the first neural network model.

[0018] Based on this approach, the first neural network model is continuously fine-tuned and iteratively optimized by using the code locations identified in actual detection and their corresponding runtime data as training samples. This allows the model to continuously learn code defect patterns and memory leak characteristics in real-world scenarios. This enhances the relevance and coverage of the model's generated parameterized test scripts, further improving the accuracy of subsequent memory detection.

[0019] In another possible implementation, runtime data of the code under test is monitored, including: monitoring the dynamic memory behavior characteristics and resource consumption information of the code under test; wherein, the dynamic memory behavior characteristics include at least one of memory snapshots, object lifecycle data, reference chain relationship graphs, and memory usage growth rate per unit time.

[0020] Based on this solution, by comprehensively monitoring the dynamic memory behavior and resource consumption information of the code under test, especially multi-dimensional indicators such as memory snapshots, object lifecycle data, reference chain graphs, and memory usage growth rates, the memory usage patterns during program runtime can be characterized from different levels. This allows for the identification of memory leaks caused by various factors, thereby improving the accuracy of memory detection.

[0021] Secondly, embodiments of this application also provide a memory leak detection device, which includes a static scanning engine configured to: acquire code to be tested; an intelligent generation module configured to: use the code to be tested as input to a first neural network model, and use the first neural network model to determine a parameterized test script for the code to be tested; a monitoring module configured to: run the parameterized test script; the monitoring module is further configured to: monitor runtime data of the code to be tested during the execution of the parameterized test script; the runtime data is used to determine whether a memory leak has occurred; the monitoring module is further configured to: determine the location of the code in the code to be tested that causes the memory leak based on the runtime data in the case of a memory leak; the monitoring module is further configured to: generate a leak detection report; the leak detection report includes the code location and the test execution path.

[0022] In one possible implementation, the static scanning engine is configured to: acquire first target code, which is any code segment in the source code; determine second target code in the first target code that conforms to memory leak characteristics based on the first target code and a preset memory leak feature pattern; perform syntax parsing on the second target code to generate a first target structure tree for the second target code; the first target structure tree is used to reflect the syntactic structure relationship of the second target code; match the first target structure tree with structured memory leak detection rules in a preset rule base to obtain the code to be tested; the code to be tested is a code segment in the first target code that has a potential memory leak risk.

[0023] In one possible implementation, the monitoring module is further configured to: determine the third target code in the code to be tested based on the matching relationship between runtime data and preset exception judgment conditions; use the second target structure tree as the input of the second neural network model, and use the second neural network model to obtain at least one code defect rule and at least one memory leak code location; wherein, the second target structure tree is used to characterize the structural relationship of the third target code.

[0024] In one possible implementation, the monitoring module is further configured to: acquire at least two memory snapshots of the code under test during the execution of the parameterized test script; perform comparative analysis on the at least two memory snapshots to acquire at least one target object type; determine the target object type as an abnormal object type if the number of instances or the total memory usage of the target object type shows a monotonically increasing trend between the two snapshots; and determine a third target code in the code under test based on the creation location and / or reference holding path of at least one abnormal object type.

[0025] In one possible implementation, a building module is further included, configured to: acquire multiple raw code features and corresponding remediation methods for each raw code feature; the raw code features are used to characterize structured code fragments with preset memory leak feature patterns; the raw code features include a first type of code feature and a second type of code feature; the first type of code feature is a structured code feature extracted based on known memory leak issues in open-source code repositories and vulnerability databases; the second type of code feature is a structured code pattern extracted from historical memory leak cases, which are determined based on runtime monitoring data; based on the first type of code feature and the second type of code feature and a preset rule template, memory leak detection rules are generated; and multiple memory leak detection rules and multiple remediation methods are stored in a preset rule base.

[0026] In one possible implementation, an update module is also included, which is configured to: evaluate multiple code defect rules to obtain the evaluation results corresponding to each code defect rule; when the evaluation results meet the preset rule entry conditions, add at least one of the multiple code defect rules as a memory leak detection rule to the preset rule library.

[0027] In one possible implementation, the update module is further configured to: construct training samples based on code locations and their corresponding runtime data; and fine-tune the first neural network model using the training samples to update the first neural network model.

[0028] In one possible implementation, the monitoring module is configured to monitor the memory dynamic behavior characteristics and resource consumption information of the code under test; wherein the memory dynamic behavior characteristics include at least one of memory snapshots, object lifecycle data, reference chain relationship graphs, and memory usage growth rate per unit time.

[0029] Thirdly, embodiments of this application also provide a computing device, including: a processor and a memory; the processor and the memory are coupled; the memory is used to store program instructions; the processor is used to execute the program instructions to perform the method as described in any of the first aspects above.

[0030] Fourthly, embodiments of this application provide a chip for performing the methods described in any of the first aspects above.

[0031] Fifthly, embodiments of this application provide a computer-readable storage medium storing computer-executable instructions, which, when executed by a computer, implement the method as described in any of the first aspects.

[0032] In a sixth aspect, embodiments of this application provide a program product including a computer program that, when executed by a processor, implements the method as described in any of the first aspects. Attached Figure Description

[0033] Figure 1 This is a schematic diagram illustrating a memory leak scenario provided in an embodiment of this application; Figure 2 This is a schematic diagram of the first process of a memory leak detection method provided in an embodiment of this application; Figure 3 This is a second flowchart illustrating a memory leak detection method provided in an embodiment of this application; Figure 4 This is a schematic diagram of a training method for a first neural network model provided in an embodiment of this application; Figure 5 This is a schematic diagram of a process for obtaining third object code provided in an embodiment of this application; Figure 6 This is a flowchart illustrating a dynamic update method provided in an embodiment of this application; Figure 7 This is a schematic diagram of a process for constructing a preset rule base provided in an embodiment of this application; Figure 8 This is a schematic diagram of a memory leak detection method provided in an embodiment of this application; Figure 9 This is a schematic diagram of the third process of a memory leak detection method provided in an embodiment of this application; Figure 10 This is a schematic diagram of a memory leak detection device provided in an embodiment of this application; Figure 11 This is a schematic diagram of a computing device provided in an embodiment of this application. Detailed Implementation

[0034] The technical solutions of the embodiments of this application will now be described with reference to the accompanying drawings. To facilitate a clear description of the technical solutions of the embodiments of this application, the use of terms such as "first," "second," etc., in the embodiments of this application is for illustrative purposes and to distinguish the objects being described. There is no particular order between them, nor does it indicate a specific limitation on the number of devices in the embodiments of this application, and they do not constitute any limitation on the embodiments of this application.

[0035] To enable those skilled in the art to better understand the technical solutions in this application, the technical solutions in the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of this application, and not all embodiments. Based on the embodiments in this application, all other embodiments obtained by those of ordinary skill in the art without creative effort should fall within the scope of protection of this application.

[0036] It should be noted that many specific details are set forth in the following description in order to provide a full understanding of this application. However, this application may also be implemented in other ways different from those described herein. Therefore, the scope of protection of this application is not limited to the specific embodiments disclosed below.

[0037] The following explanations of the technical terms mentioned in the embodiments of this application are provided to facilitate understanding by those skilled in the art.

[0038] A memory leak occurs when a program dynamically allocates memory during runtime, but fails to reclaim and reuse it after use. As the program continues to run, unreleased memory accumulates, eventually exhausting available memory resources, leading to performance degradation, slow response times, or even program crashes.

[0039] An abstract syntax tree (AST) is a tree-like representation of code structure that parses code into a tree structure composed of nodes and edges according to the grammatical rules of a language. Each node represents a syntactic construct in the source code, such as a variable declaration, function call, or control statement. Edges represent syntactic inclusion or structural dependencies between nodes; for example, the "function definition" node may be connected to child nodes such as "parameter list" and "function body" via edges.

[0040] A parameterized test script is an automatically executable test program that can accept different input parameters and repeatedly execute them for various test scenarios. In this solution, the script is generated by a neural network model based on the code under test, and is used to drive the target code to run, simulating various execution paths and input conditions to fully expose potential memory leaks.

[0041] The embodiments of this application will now be described with reference to the accompanying drawings.

[0042] Memory is a critical resource in computing devices used to temporarily store data and instructions required for program execution. During program execution, the system dynamically allocates memory space as needed to store objects, variables, cached data, etc. When the program no longer needs this data, it should actively release the corresponding memory so that the system can reclaim it and reallocate it to other tasks, thereby ensuring the efficient and stable operation of the program.

[0043] However, in actual operation, due to programming logic flaws or improper resource management, the risk of memory leaks is widespread. A memory leak refers to the failure to properly reclaim memory allocated by a program after use, resulting in this memory being occupied for a long time. Its causes include not only explicit failure to release resources (such as file handles, database connections not being closed, or dynamically allocated memory not being manually released), but also implicit uncontrolled reference relationships. For example, in a reference-counting environment, circular references can form between objects, causing their reference counts to fail to reach zero even when they are no longer used externally, preventing the garbage collection mechanism from reclaiming their memory. These "forgotten" memory blocks accumulate as the program continues to run, gradually reducing available memory, leading to slower system response, frequent garbage collection, service interruptions, and in severe cases, even program crashes or system downtime.

[0044] The following is combined Figure 1 The following example illustrates how a memory leak can occur due to failure to release resources in a timely manner.

[0045] Figure 1 This is a schematic diagram of a memory leak scenario provided in an embodiment of this application.

[0046] like Figure 1 As shown, when a computing device processes business logic, it assumes that it needs to write data related to four user requests into a global cache, namely data A, data B, data C, and data D, to facilitate fast retrieval and reuse in subsequent processes. Once a user request is processed, its corresponding cached data should be removed from the global cache to release the occupied memory resources and ensure efficient memory recycling.

[0047] For example, after the first and second user requests are processed—that is, when the data A corresponding to the first user request and the data B corresponding to the second user request are no longer needed—ideally, the corresponding data entries should be removed from the global cache, releasing the references to these data objects so that the garbage collector can identify and reclaim the corresponding memory space. However, in reality, due to some programming error or logical flaw, the data B for the second user request may not be correctly removed from the global cache. In other words, the global cache still holds a reference to this data. As long as any active reference exists, the garbage collection mechanism will consider this memory still in use and therefore will not reclaim it.

[0048] As the system continues to run, cached entries that are not released in a timely manner accumulate, gradually reducing available memory resources. Although this data is no longer used by any business logic, the system cannot detect its invalidity because the references are not broken, ultimately causing a memory leak.

[0049] Therefore, it is necessary to introduce a proactive memory detection mechanism to determine whether memory leaks have occurred, so as to ensure that the system can promptly detect and locate resource retention problems caused by unreleased object references during long-term operation, prevent invalid data from continuously occupying memory, and thus ensure the stability of the system.

[0050] Therefore, this application provides a method for detecting memory leaks, comprising: acquiring code to be tested for memory leak detection; using the code to be tested as input to a first neural network model, and generating a parameterized test script for the code to be tested using the first neural network model; the parameterized test script is a tool used to drive the execution of the code to be tested; monitoring runtime data of the code to be tested during the execution of the parameterized test script; the runtime data is used to determine whether memory leaks have occurred; if memory leaks have occurred, determining the location of the code in the code to be tested that caused the memory leak based on the runtime data; generating a leak detection report; the leak detection report includes the code location, test execution path, and remediation suggestions.

[0051] The following describes a specific implementation of a memory leak detection method with reference to the accompanying drawings.

[0052] Figure 2 This is a first flowchart illustrating a memory leak detection method provided in an embodiment of this application.

[0053] like Figure 2 As shown, the method for detecting memory leaks includes the following steps: S1: Obtain the code to be tested.

[0054] Figure 3 This is a second flowchart illustrating a memory leak detection method provided in an embodiment of this application.

[0055] like Figure 3 As shown, step S1 includes steps S11-S14.

[0056] S11: Obtain the first target code.

[0057] The first target code is any code snippet from the source code. This snippet can be the Python code to be detected, or a function, class, or module written in other programming languages ​​that support dynamic memory management (such as Java, Go, JavaScript, etc.). The first target code usually involves critical operations that may cause memory leaks, such as: the use of global or static variables, the implementation of caching mechanisms, the registration and unregistration of event listeners, the opening and closing of resource handles, and the maintenance of references to long-lived objects. By selecting such potentially risky code units as detection targets, the targeting and effectiveness of memory leak detection can be improved.

[0058] Continuing with the example above, obtain the first target code X involved in a certain Python service.

[0059] S12: Based on the first target code and the preset memory leak feature pattern, determine the second target code in the first target code that meets the memory leak feature.

[0060] The first target code is a code snippet from the source code. However, in real-world projects, there are numerous such snippets to be inspected, and some may contain complex logic or nested structures, resulting in issues such as large data volume and a wide detection range. To improve detection efficiency and accuracy, the first target code can be initially screened using preset memory leak feature patterns.

[0061] The initial screening can be achieved using regular expression matching. Regular expression matching refers to the technique of using regular expressions to perform pattern recognition and string matching on source code text. By pre-defining regular expression rules for typical code patterns related to memory leaks, code can be quickly scanned and potentially risky code segments can be located without fully parsing the syntax structure.

[0062] Optionally, regular expression matching can be used to obtain second target code that matches the memory leak characteristics in the first target code based on the first target code and a preset memory leak feature pattern.

[0063] Memory leak characteristic patterns may include at least one of the following: global cache write operations, maintenance of references to long-lived objects, mismatch between resource opening and closing, and lack of unregistration logic after event listener registration.

[0064] Continuing with the example above, after obtaining the first target code X, the first target code X is compared with the preset memory leak feature pattern by regular expression matching to identify the code area in the first target code X that has potential leakage risk. The high-risk area matched is determined as the second target code X1. In this way, subsequent detection resources can be preferentially allocated to the second target code X1 to improve the detection efficiency of potential memory leak behavior.

[0065] S13: Parse the second target code to generate the first target structure tree of the second target code.

[0066] A structure tree, or Abstract Syntax Tree (AST), is a tree-like representation of the syntactic structure of source code. The process of generating a structure tree involves: first, lexical analysis of the code, breaking down the character sequence into meaningful syntactic units (tokens); then, syntactic analysis, organizing these units into a tree structure according to the language's grammatical rules. Each node represents a syntactic construct in the code, such as a class definition, function declaration, assignment statement, or conditional statement. This process can be achieved by calling syntax parsing tools or libraries specific to the programming language. For example, Python can use the built-in `ast` module or the `lib2to3` library, Java can use the Eclipse JDT or `javalang` tools, and JavaScript can use parsers like `esprima`. Alternatively, a general-purpose compiler framework (such as ANTLR or Tree-sitter) can be used in conjunction with the corresponding language's syntax rule files to achieve cross-language, high-precision syntax parsing.

[0067] Continuing with the example above, taking Python code as an example, the selected second target code X1 is input into Python's ast module. After lexical and syntactic analysis, the module parses it into a hierarchical tree structure, namely the first target tree structure X2.

[0068] S14: Match the first target structure tree with the structured memory leak detection rules in the preset rule base to obtain the code to be tested.

[0069] The first target structure tree is matched with the structured memory leak detection rules in the preset rule base to obtain the code to be tested.

[0070] The pre-built rules database is a comprehensive knowledge base that is pre-built and continuously maintained, covering multiple dimensions of memory leak characteristic sources. For example, it includes memory security defect information obtained by regularly crawling public vulnerability platforms (such as CVE and NVD) based on industry-recognized common leak pattern library, features of fixed memory leak cases mined and extracted from the historical commit records of mainstream open source projects, and vulnerability detection rules transformed by analyzing and classifying abnormal memory behavior during historical runtime.

[0071] The code to be tested is a code segment in the first target code that has a potential risk of memory leaks. Optionally, the code to be tested can be obtained by using subtree isomorphism or tree edit distance algorithms, or by using a model. The following explanation uses the tree edit distance algorithm as an example.

[0072] The system performs structural matching between the first target structure tree and various memory leak pattern templates in the rule base. Each memory leak rule in the preset database exists as a structured pattern template, such as "resources are opened but not closed," "two-way references between objects with no release logic," and "written to the global cache but no deletion operation." By structurally matching the first target structure tree with these pattern templates and calculating their similarity scores, combined with contextual analysis (such as determining whether `.close()` is called in all paths after `open()`, or whether a `del` operation occurs after cache writing), the system comprehensively evaluates whether the code exhibits high-risk characteristics such as unreleased resources, circular references, or global state retention. If a match is successful and the similarity exceeds a preset threshold, the code snippet is determined to have a high risk of memory leaks and is thus identified as code to be tested for subsequent test script generation and runtime monitoring.

[0073] S2: Using the code to be tested as input to the first neural network model, generate a parameterized test script for the code to be tested using the first neural network model.

[0074] The first neural network model is a pre-trained model, meaning it is trained on a large-scale dataset before use. To ensure the generalization ability of the first neural network model, it needs to be trained on a large amount of data. This pre-trained first neural network model is used to obtain the test scripts for the code to be tested.

[0075] Figure 4 This is a schematic diagram of a training method for a first neural network model provided in an embodiment of this application.

[0076] like Figure 4 As shown, the training method for the first neural network model includes the following steps: S401: Obtain the training set.

[0077] The training set includes at least one sample test code and a target parameterized test script corresponding to each sample test code.

[0078] S402: Train the neural network model by using at least one sample test code as input to the first neural network model and the target parameterized test script corresponding to each sample test code as output to the neural network model.

[0079] In one example, at least one sample test code is input into the original neural network model. Using the original neural network model, the output parameterized test script corresponding to the sample test code is output. Furthermore, using a preset loss function, the loss value between each output parameterized test script and each target parameterized test script is calculated. Based on the loss value, the original neural network model is continuously adjusted. When the loss value is less than a preset threshold, it means that the initial neural network model has been trained and the first trained neural network model is obtained.

[0080] After the first neural network model is trained, the code to be tested is input into the neural network model to obtain the parameterized test script of the code to be tested.

[0081] Parameterized test scripts are tools used to drive the execution of the code under test. In other words, a parameterized test script is an executable code framework used to drive the code under test to be effectively called and executed in a simulated runtime environment. Through this script, various operation paths in the code under test can be automatically triggered, especially execution flows involving high-risk behaviors such as memory allocation, object references, and resource management, providing necessary execution support for subsequent runtime data monitoring and memory leak detection.

[0082] Continuing with the example above, the code X3 to be tested is input into the first neural network model. The first neural network model analyzes the code X3 and generates a parameterized test script X4 for the code. This parameterized test script X4 incorporates a fusion of multiple testing strategies, specifically: a path coverage script to achieve multi-execution path coverage, used to traverse branches and loop structures in the code; a parameterized boundary test script designed for input parameters to verify resource management behavior under extreme values, null values, or abnormal inputs; and a function-level fuzz test script to detect unexpected memory operations, triggering potential memory leak scenarios by generating random or mutated input sequences.

[0083] S3: Run the parameterized test script.

[0084] Running parameterized test scripts refers to using the generated parameterized test scripts to dynamically test and monitor the code under test (let's say X3). This process involves running the code under test and collecting its runtime data in real time to determine if memory leaks are present.

[0085] Following the example above, run the parameterized test script X4.

[0086] S4: Monitor runtime data of the code under test during the execution of parameterized test scripts.

[0087] The runtime data includes dynamic memory behavior characteristics and resource consumption information; the dynamic memory behavior characteristics include at least one of memory snapshots, object lifecycle data, reference chain relationship graphs, and memory usage growth rate per unit time.

[0088] In one example, a memory sampling mechanism monitors the call stack during object allocation to pinpoint memory allocation hotspots and their source code locations. Simultaneously, it utilizes the GC (garbage collection) module provided by the language runtime to detect any uncollectible objects due to circular references. Through this multi-dimensional, fine-grained runtime monitoring, a comprehensive understanding of the memory behavior of the code under test during execution can be achieved.

[0089] Continuing with the example above, during the execution of the parameterized test script X4, the runtime data X5 of the code to be tested X3 is obtained.

[0090] Runtime data is used to determine whether memory leaks have occurred. By comprehensively analyzing the dynamic memory behavior characteristics and resource consumption information in the runtime data, memory leak behavior can be effectively identified.

[0091] If monitoring reveals that the number of certain object instances continues to increase after multiple identical operations and does not decrease as the scope ends, or if the reference chain graph confirms that expired objects are still strongly referenced by root objects such as global variables and static containers and cannot be reclaimed, or if memory usage shows a non-linear and continuous increase and cannot fall back to the baseline level after multiple GCs, or if temporary objects reside in memory for a long time with a lifespan far exceeding the normal logical requirements, or if the memory growth rate per unit time is significantly higher than expected and does not tend to stabilize, then it is determined to be a memory leak.

[0092] If the increase in memory usage is only a brief fluctuation during the batch processing or initialization phase and is effectively released after the task ends; or the mechanism is triggered normally and the recycling effect is obvious; or the memory usage comes from an active cache design with a clear eviction policy (such as LRU cache) and is within a controllable range; or the number of objects allocated and released is basically symmetrical and memory usage shows periodic fluctuations rather than continuous growth, then it is considered normal resource usage behavior and is not judged as a memory leak.

[0093] S5: In the event of a memory leak, determine the location of the code causing the memory leak in the code under test based on runtime data.

[0094] Continue to combine Figure 3 As shown, step S5 includes steps S51-S52.

[0095] S51: Based on the matching relationship between runtime data and preset exception judgment conditions, determine the third target code in the code to be tested.

[0096] Figure 5 This is a schematic diagram of a process for obtaining third target code provided in an embodiment of this application.

[0097] Continue to combine Figure 5 As shown, in one example, step S51 includes steps S511-S514.

[0098] S511: Obtain at least two memory snapshots of the code under test during the execution of the parameterized test script.

[0099] A memory snapshot is a complete or sampled record of the current heap memory state at a specific point in time during program execution. It includes information such as the type, number of instances, memory usage, reference relationships, and creation stacks of all active objects.

[0100] For example, during the execution of the parameterized test script, memory snapshot collection is automatically triggered based on key time points (such as before the start of the test, after multiple rounds of operations, and before the end of the test) to obtain at least two memory snapshots.

[0101] S512: Compare and analyze at least two memory snapshots to obtain the type of the target object.

[0102] The target object type refers to a specific class or data structure type that is identified as having a significant memory growth trend or abnormal residency behavior during the comparison of multiple memory snapshots. These types are usually objects that are frequently created in the system but not released in a timely manner, such as custom cache entries, event listeners, network connections, UI components, or large data containers. Through a differential comparison algorithm, the system statistically analyzes the number of instances, total memory usage, liveness status, and reference root paths of each object type at different time points, and filters out candidate types with significant changes as target object types.

[0103] It should be noted that the comparison method used in this process can be called the differential comparison algorithm, which identifies incremental changes in the number of object instances, total memory usage, or reference structure by performing differential analysis on multiple memory snapshots.

[0104] S513: If the target object type satisfies the condition that the number of instances or the total memory usage increases monotonically between two snapshots, the target object type is determined to be an abnormal object type.

[0105] An anomalous object type refers to an object type whose instance count or total memory usage shows a continuous upward trend across consecutive memory snapshots without corresponding release behavior. Specifically, if an object type has only a few instances at the start of the test, but the number of instances increases significantly after multiple rounds of operations (e.g., from 10 to thousands), and there are no obvious signs of reduction or reclamation before the end of the test, then its growth trend is considered to have a "monotonically increasing" characteristic. This behavior deviates from the normal memory usage pattern (i.e., "use and release"), indicating that this type of object may have been incorrectly held for a long time or not properly cleaned up, thus being identified as an anomalous object type and a high-risk signal of memory leaks.

[0106] S514: Determine the third target code in the code under test based on the creation location and / or reference holding path of the exception object type.

[0107] After identifying the abnormal object type, its lifecycle information is further traced to locate the code location where it was first created (such as the constructor call point or factory method). Reference chain analysis is then used to identify which variables, containers, or modules hold strong references to the object for extended periods (e.g., references from static collections, global dictionaries, or ununregistered callback functions). These code locations directly prevent the object from being garbage collected. Based on this, the code region, i.e., the third target code, is determined.

[0108] S52: Using the second target structure tree as input to the second neural network model, at least one code defect rule and at least one memory leak code location are obtained using the second neural network model.

[0109] The second target structure tree is used to represent the structural relationship of the third target code. The method for converting the third target code into the second target structure tree can refer to the content of step S13 above, and will not be repeated here.

[0110] The second neural network model is a pre-trained model, meaning it is trained on a large-scale dataset before use. This second neural network model is used to pinpoint the specific location of memory leaks. To ensure the generalization ability of the second neural network model, it needs to be trained on a large amount of data.

[0111] The training method for the second neural network model can refer to the training method for the first neural network model described above, and will not be repeated here.

[0112] Following the example above, the second target structure tree is input into the second neural network model to obtain code defect rules K1, K2, and K3, as well as the code locations of memory leaks L1 and L2.

[0113] S6: Generate a leak detection report.

[0114] A leak detection report presents the results of memory leak detection. A leak detection report may include the code location and test execution path, or it may include the code location, test execution path, and remediation recommendations.

[0115] In one example, continue combining Figure 3 As shown, step S6 includes steps S61-S62.

[0116] S61: Obtain the test execution path.

[0117] The test execution path characterizes the execution trajectory from the starting point that triggers the execution of the code under test to the specified location when the parameterized script is run. This path may include the method call sequence, key parameter values, and the operational context that caused the leak.

[0118] Continuing with the example above, obtain the test execution path X61' and the test execution path X62'.

[0119] S62: Generate a leak detection report that includes code location and test execution path.

[0120] Following the example above, generate a leak detection report X7 that includes the code location of the memory leak L1, the code location of the memory leak L2, the test execution path X61', and the test execution path X62'.

[0121] Optionally, steps S63 and S64 may be included, considering that although developers may be able to identify memory leaks, they may have difficulty determining the specific fix.

[0122] In another example, after obtaining the test execution path in step S61, steps S63-S64 are also included.

[0123] S63: Fix suggestions for obtaining code location.

[0124] The remediation suggestions guide developers on how to fix code defects that cause memory leaks. These suggestions can be based on the type and context of the code location, matching corresponding remediation patterns from a pre-defined rule base (e.g., for unclosed file resources, recommend using a `with` statement or explicitly calling `.close()`; for circular references, recommend introducing a weak reference (`weakref`) or manually dereferencing it at an appropriate time); or they can be automatically generated by the system based on code semantics and best practices. The specific generation method is not limited here.

[0125] Following the example above, we obtain the repair suggestion X61 for the memory leak code location L1, the memory leak code location L2, and the repair suggestion X62 for the memory leak code location L2.

[0126] S64: Generate a leak detection report that includes code location, test execution path, and remediation suggestions.

[0127] Following the example above, a leak detection report X7 is generated, which includes the code location of the memory leak L1, the code location of the memory leak L2, the test execution path X61', the test execution path X62', the repair suggestion X61”, and the repair suggestion X62”.

[0128] In summary, by combining preset memory leak characteristic patterns with code structure analysis, the code to be tested can be initially obtained. Based on this, a neural network model is used to automatically generate parameterized test scripts, and combined with runtime memory behavior monitoring, which helps to trigger potential memory leak scenarios more comprehensively, locate memory leak points more accurately, and effectively improve the accuracy of detection.

[0129] The above example illustrates the determination of a single code location. In practice, multiple code locations may be involved. The methods for determining multiple code locations are as described in steps S1-S6 above, and will not be repeated here.

[0130] Optionally, to improve the accuracy of memory leak detection, a feedback closed-loop mechanism is introduced during the dynamic detection process to continuously optimize the detection capability based on the actual leak problems found. Specifically, in another embodiment, after executing steps S1-S5, the following operations can be further performed: S7: Dynamically updates the preset rule base and the first neural network model based on multiple code locations.

[0131] Figure 6 This is a flowchart illustrating a dynamic update method provided in an embodiment of this application.

[0132] like Figure 6 As shown, step S7 includes S71-S72.

[0133] S71: Dynamically updates the preset rule base based on multiple code locations.

[0134] After completing a full memory leak detection and locating the code location, the system not only outputs a detection report but also further summarizes and refines these real-world leak cases to generate potential code defect rules. These rules are derived from leak patterns that have been verified as effective in actual projects. By systematically evaluating multiple such rules, their universality, stability, and differences from existing rules are assessed. High-priority rules with long-term usability are then selected to enhance the coverage of the pre-defined rule base.

[0135] The following will continue to combine Figure 6 As shown, step S71 includes steps S711-S712.

[0136] S711: Evaluate multiple code defect rules to obtain the evaluation results for each code defect rule.

[0137] Specifically, candidate defect rules derived from multiple code locations are extracted from historical detection results. These rules have been processed through pattern abstraction and are represented by structured code features (such as "assigning values ​​to a class attribute dictionary without deletion statements" and "not calling the unregister method after registering a listener"). Subsequently, each candidate rule is evaluated from multiple dimensions.

[0138] Optionally, the reproducibility of the rule in different projects (i.e., whether it can match similar leak instances in multiple independent codebases), the breadth of applicability in various code structures (whether it covers multiple classes, functions or language variants), the false positive and false negative rates (precision and recall on the validation set), whether it has semantic duplication or conflict with existing rules in the preset rule base, and whether its structure can be accurately modeled as an abstract syntax tree (AST) template or control flow pattern (i.e. whether it has good parsing and matching stability).

[0139] Based on the above indicators, the system generates a comprehensive evaluation result for each candidate rule, which is usually expressed in the form of a quantitative score or grade, and is used for subsequent rule screening and database entry decisions.

[0140] S712: When the evaluation result meets the preset rule entry conditions, add at least one rule from at least one code defect rule as a memory leak detection rule to the preset rule library.

[0141] The preset rule entry conditions may include at least one of the following: comprehensive score higher than the threshold, false alarm rate lower than the allowable upper limit, successful reproduction in multiple independent projects, clear and modelable structural features, and no semantic redundancy with the existing rule base.

[0142] Continuing with the example above, suppose there are two code defect rules that meet the preset rule inclusion criteria, namely code defect rule Y and code defect rule Z. Add code defect rule Y and code defect rule Z as memory leak detection rules to the preset rule library.

[0143] In this way, the rules in the preset rule base can be continuously expanded, ensuring the generalization ability of the preset rule base and improving the accuracy of subsequent memory leak detection.

[0144] S72: Dynamically update the first neural network model based on code location.

[0145] Continue to combine Figure 6 As shown, step S72 includes steps S721-S722.

[0146] S721: Construct training samples based on code locations and their corresponding runtime data.

[0147] The code snippets at the code locations are extracted during the detection process and combined with their runtime data, including the abstract syntax tree structure, control flow path, variable reference relationships, and dynamic memory behavior features collected at runtime (such as memory snapshot changes, object lifecycle, reference chain graph, memory growth trend, etc.), to construct structured training samples.

[0148] S722: Fine-tune the first neural network model using training samples to update the first neural network model.

[0149] Newly constructed training samples are added to the incremental training set of the model, and the parameters of the first neural network model are updated using transfer learning or online fine-tuning strategies. During fine-tuning, the first neural network model focuses on enhancing its feature extraction and matching capabilities for new leakage patterns while maintaining its existing knowledge. After training, the model's performance is evaluated on an independent validation set, including the coverage of generated test scripts, the recall rate for known leakage patterns, and the ability to control false positives in non-leaking code. Once the performance metrics meet expectations, the updated model is deployed as the latest version for subsequent analysis of code to be tested and script generation, thereby achieving continuous evolution of detection capabilities.

[0150] In summary, by using multiple code locations discovered in actual detection as feedback sources, the preset rule base and the first neural network model are dynamically updated in a coordinated manner. This allows the system to continuously learn and evolve from real-world scenarios, which not only improves the detection rate of known leakage patterns but also enhances the adaptability to new or variant leakage patterns, thereby significantly improving the overall accuracy of memory leak detection.

[0151] Before performing step S1 of the above embodiment, a preset rule base for memory leak detection can be pre-built. The following section combines... Figure 7The specific implementation method for constructing this rule base is described in detail.

[0152] Figure 7 This is a schematic diagram of a process for constructing a preset rule base provided in an embodiment of this application.

[0153] like Figure 7 As shown, the method for constructing a preset rule base includes the following steps: S701: Obtain multiple original code features and the corresponding repair methods for each original code feature.

[0154] To construct high-quality memory leak detection rules, we first collect representative raw code features and their corresponding remediation solutions. Raw code features are used to characterize structured code fragments with preset memory leak feature patterns, accurately reflecting the syntax and semantic structure of typical leak scenarios.

[0155] The original code features include a first type of code features and a second type of code features. The first type of code features are structured code features extracted from known memory leak issues in open-source code repositories and vulnerability databases. The second type of code features are structured code patterns extracted from historical memory leak cases, which are determined based on runtime monitoring data.

[0156] For example, the repair method N corresponding to the first type of code feature M1, the second type of code feature M2, and the original code feature M is obtained.

[0157] S702: Generate memory leak detection rules based on each type of first-class code feature, each type of second-class code feature, and preset rule templates.

[0158] Since the aforementioned raw code features may originate from different sources, multiple raw code features will be heterogeneous. A unified feature parsing tool can be used for standardization and structuring to achieve a unified representation of these heterogeneous features. This unified feature parsing tool may include Natural Language Processing (NLP) techniques, Abstract Syntax Tree (AST) analysis, CodeDiff, and other program analysis methods, capable of transforming code features from different sources (such as text descriptions, syntactic structures, and change contexts) into a unified, structured intermediate representation.

[0159] The preset rule template is a standardized rule description framework used to guide how to transform raw code features into executable and reusable structured detection rules. This template defines the core components and organizational form of the rules, ensuring that the generated detection rules are consistent, scalable, and maintainable. The preset rule template may include at least one of the following: matching patterns (such as abstract syntax tree (AST) structures, regular expressions, control flow paths, or data dependency chains), triggering conditions (such as failure to perform a release operation after a specific API call, long-term object references without cleanup logic), scope (such as function-level, class-level, or global scope), risk level (such as high, medium, and low, based on the severity and scope of the leak), applicable language or framework (such as Python, Java, specific web frameworks, etc.), and contextual constraints (such as whether it is within an exception handling block, or whether a multi-threaded environment is involved).

[0160] Continuing with the example above, the first type of code feature M1 and the second type of code feature M2 are standardized and structured using a unified feature parsing tool to achieve a unified representation of heterogeneous features. Based on this, and with a preset rule template, two memory leak detection rules are generated: memory leak detection rule K1 and memory leak detection rule K2.

[0161] S703: Store each memory leak detection rule and each repair method in the preset rule base.

[0162] Following the example above, memory leak detection rule K1 and its corresponding repair method N1, as well as memory leak detection rule K2 and its corresponding repair method N2, are stored in the preset rule base.

[0163] It should be noted that memory leak detection rules and remediation methods can be stored in one rule base as shown in the example above, or they can be stored in two databases; no specific limitation is made here.

[0164] Figure 8 This is a schematic diagram of a memory leak detection method provided in an embodiment of this application.

[0165] like Figure 8 As shown, memory leak detection methods can include four processing stages: static scanning, intelligent test generation, dynamic monitoring, and dynamic update. These four stages work together to detect memory leaks. The following section will discuss this in conjunction with... Figure 8 As shown, the method for detecting memory leaks is explained in detail.

[0166] In this method, the first target code (such as a function, class, or module written in languages ​​like Python, Java, or Go) is taken as input and flows through the four stages mentioned above in sequence, ultimately generating a memory leak detection report. The memory leak detection report can include the code location of the leak point, the test execution path that triggered the leak, and corresponding remediation suggestions.

[0167] Specifically, in the static scanning phase, the first target code undergoes preliminary screening. This phase can include two sub-processes. On the one hand, using methods such as regular expression matching, the code is compared with preset memory leak characteristic patterns (such as resources opened without being closed, event listeners not being unregistered, and global cache not being cleared) to filter out code areas with potential risks, i.e., the second target code. On the other hand, the filtered second target code is parsed to generate its abstract syntax tree (AST), and further matched with a structured memory leak detection rule base to accurately identify code with memory management defects, i.e., the code to be tested.

[0168] It should be noted that, continuing to combine Figure 3 As shown, in addition to the structured analysis based on abstract syntax trees mentioned above, code smell detection can be further introduced as a supplementary method. By integrating static analysis tools such as Flake8, Bandit, and Pylint, the code can be scanned from multiple dimensions to identify patterns such as unused variables, incomplete exception handling, dangerous function calls, and improper resource management. These "code smells" are often the initial stages of potential defects (including memory leaks). For example, Pylint can detect classes that have not called their parent class destructors, and Bandit can warn of unclosed file handles.

[0169] The specific details of the static scanning stage can be further referred to in steps S11-S14 above, and will not be elaborated here.

[0170] During the intelligent test generation phase, the code to be tested, output from the static scanning phase, is used as input. A first neural network model is then used to automatically generate parameterized test scripts adapted to the code structure and risk characteristics. This first neural network model can be trained based on historical leak cases, code semantic features, and execution path patterns. It can generate targeted test execution sequences for different types of memory leak risks (such as unreleased resources, circular references, cache accumulation, etc.). Specifically, the parameterized test scripts not only cover conventional execution paths but also proactively construct boundary conditions, abnormal exit scenarios, long-running loops, and high-concurrency call stress scenarios to fully stimulate potential memory leak behaviors.

[0171] The specific details of the intelligent test generation phase can be found in step S2 above, and will not be elaborated further here.

[0172] During the dynamic monitoring phase, the parameterized test scripts generated in the intelligent test generation phase are executed, and the code to be tested is monitored in real time during execution. Specifically, runtime data is automatically collected at key time points in program execution. This runtime data includes dynamic memory behavior characteristics and resource consumption information. The dynamic memory behavior characteristics include at least: comparisons of memory snapshots, object lifecycle data, reference chain graphs, and the memory usage growth rate per unit time. The resource consumption information covers system resource usage such as CPU utilization, changes in the number of threads, and file handles or network connections, used to help determine whether memory growth is accompanied by abnormal resource retention.

[0173] For example, during the execution of the parameterized test script X4, the code X3 to be tested undergoes multiple rounds of operation, and memory snapshots are automatically triggered at key nodes such as before the test starts, after multiple rounds of loops, and before the test ends, obtaining at least two memory snapshots (corresponding to step S511 above). Subsequently, by performing differential comparative analysis on these snapshots (corresponding to step S512), the target object type with a significant increase in the number of instances or memory usage (such as cache entries, event listeners, unclosed connections, etc.) is identified. If the target object type shows a monotonically increasing trend in consecutive snapshots and there is no corresponding release behavior (corresponding to step S513), it is determined to be an abnormal object type, considered a high-risk signal of memory leak. Further, based on the creation stack and reference holding path of the abnormal object type (e.g., strongly referenced by static containers, global variables, or ununregistered callback functions), the code area that causes the object to be unable to be reclaimed is accurately located, thereby determining the third target code (corresponding to step S514).

[0174] Based on this, the third target code is converted into a second target structure tree (construction method refers to step S13), and used as input to the second neural network model. This model is pre-trained on large-scale real leak samples and can output code defect rules matching the current leak pattern (such as "missing eviction logic after cache write" and "no unregistration after listener registration") and specific memory leak code locations, i.e., code locations (such as function names, line numbers, variable names, etc.) (corresponding to step S52), based on the code location. Further, the test execution path is obtained based on the code location, and a leak detection report is generated based on the code location and the test execution path.

[0175] The specific details of the dynamic monitoring phase can be found in steps S3-S6 above, and will not be elaborated further here.

[0176] In the dynamic update phase, in order to improve the accuracy of memory leak detection, a feedback closed-loop mechanism is introduced in the dynamic detection process. The detection capability is continuously optimized based on the actual leak problems found. Specifically, the code positions in the generated runtime data are used as new training samples and injected into the first neural network model for dynamic updates, as well as updating the preset rule base.

[0177] The specific details of the dynamic update phase can be found in step S7 above, and will not be elaborated further here.

[0178] In summary, by combining preset memory leak characteristic patterns with code structure analysis, the code to be tested can be initially obtained. Based on this, a neural network model is used to automatically generate parameterized test scripts, and combined with runtime memory behavior monitoring, which helps to trigger potential memory leak scenarios more comprehensively, locate memory leak points more accurately, and effectively improve the accuracy of detection.

[0179] Corresponding to the aforementioned embodiments of the memory leak detection method, this application also provides a complete embodiment of the memory leak detection method.

[0180] Figure 9 This is a schematic diagram of the third process of a memory leak detection method provided in an embodiment of this application.

[0181] like Figure 9 As shown, the method for detecting memory leaks includes the following steps: S901: Static scanning engine obtains the first target code.

[0182] The specific details of step S901 can be found in step S11 above, and will not be repeated here.

[0183] S902: The static scanning engine determines the first target structure tree based on the first target code.

[0184] The specific details of step S902 can be found in steps S12-S13 above, and will not be repeated here.

[0185] S903: The static scanning engine matches the first target structure tree with the structured memory leak detection rules in the preset rule base to obtain the code to be tested.

[0186] The specific details of step S903 can be found in step S14 above, and will not be repeated here.

[0187] S904: The intelligent generation module takes the code to be tested as input to the first neural network model and uses the first neural network model to generate a parameterized test script for the code to be tested.

[0188] The specific details of step S904 can be found in step S2 above, and will not be repeated here.

[0189] S905: The monitoring module executes parameterized test scripts.

[0190] S906: The monitoring module monitors the runtime data of the code under test during the execution of the parameterized test script.

[0191] The specific details of steps S905-S906 can be found in step S4 above, and will not be repeated here.

[0192] S907: Determine whether a memory leak has occurred based on runtime data.

[0193] S908: In the event of a memory leak, the monitoring module determines the location of the code causing the memory leak in the code under test based on runtime data.

[0194] The specific details of steps S907-S908 can be found in step S5 above, and will not be repeated here.

[0195] S909: The monitoring module generates a leak detection report.

[0196] The specific details of step S909 can be found in step S6 above, and will not be repeated here.

[0197] S910: The update module dynamically updates the preset rule base based on code location.

[0198] The specific details of step S910 can be found in step S71 above, and will not be repeated here.

[0199] S911: The update module dynamically updates the first neural network model based on the code location.

[0200] The specific details of step S911 can be found in step S72 above, and will not be repeated here.

[0201] The order of steps S910-S911 is not specifically limited.

[0202] In summary, by combining preset memory leak characteristic patterns with code structure analysis, the code to be tested can be initially obtained. Based on this, a neural network model is used to automatically generate parameterized test scripts, and runtime memory behavior monitoring is combined to obtain the code location where memory leaks occur, which can effectively improve the accuracy of detection.

[0203] Corresponding to the embodiments of the aforementioned memory leak detection method, this application also provides embodiments of a memory leak detection device.

[0204] Figure 10 This is a schematic diagram of a memory leak detection device provided in an embodiment of this application.

[0205] like Figure 10 As shown, the memory leak detection 1000 includes: a static scanning engine 1001, an intelligent generation module 1002, a monitoring module 1003, a building module 1004, and an update module 1005.

[0206] The static scanning engine 1001 is configured to acquire the code to be tested; the intelligent generation module 1002 is configured to use the code to be tested as input to a first neural network model and determine the parameterized test script for the code to be tested using the first neural network model; the monitoring module 1003 is configured to run the parameterized test script; the monitoring module 1003 is also configured to monitor the runtime data of the code to be tested during the execution of the parameterized test script; the monitoring module 1003 is also configured to determine the location of the code causing the memory leak in the code to be tested based on the runtime data in the event of a memory leak; the monitoring module 1003 is also configured to generate a leak detection report; the leak detection report includes the code location and the test execution path.

[0207] In one possible implementation, the static scanning engine 1001 is specifically configured to: acquire first target code, which is any code segment in the source code; determine second target code in the first target code that conforms to memory leak characteristics based on the first target code and a preset memory leak feature pattern; parse the second target code to generate a first target structure tree for the second target code; the first target structure tree is used to reflect the syntactic structure relationship of the second target code; match the first target structure tree with structured memory leak detection rules in a preset rule base to obtain the code to be tested; the code to be tested is a code segment in the first target code that has a potential memory leak risk.

[0208] In one possible implementation, the monitoring module 1003 is further configured to: determine the third target code in the code to be tested based on the matching relationship between runtime data and preset exception judgment conditions; use the second target structure tree as the input of the second neural network model, and use the second neural network model to obtain at least one code defect rule and at least one memory leak code location; wherein, the second target structure tree is used to characterize the structural relationship of the third target code.

[0209] In one possible implementation, the monitoring module 1003 is further configured to: acquire at least two memory snapshots of the code under test during the execution of the parameterized test script; perform comparative analysis on the at least two memory snapshots to acquire at least one target object type; determine that the target object type is at least one abnormal object type if the number of instances or the total memory usage of the target object type shows a monotonically increasing trend between the two snapshots; and determine a third target code in the code under test based on the creation location and / or reference holding path of the abnormal object type.

[0210] In one possible implementation, a construction module 1004 is also included. This construction module is configured to: acquire multiple raw code features and corresponding repair methods for each raw code feature; the raw code features are used to characterize structured code fragments with preset memory leak feature patterns; the raw code features include a first type of code features and a second type of code features; the first type of code features are structured code features extracted based on known memory leak issues in open-source code repositories and vulnerability databases; the second type of code features are structured code patterns extracted from historical memory leak cases, which are determined based on runtime monitoring data; generate memory leak detection rules based on the first type of code features and the second type of code features and preset rule templates; and store multiple memory leak detection rules and multiple repair methods in a preset rule base.

[0211] In one possible implementation, the update module 1005 is configured to: evaluate multiple code defect rules and obtain the evaluation results corresponding to each code defect rule; when the evaluation results meet the preset rule entry conditions, add at least one of the multiple code defect rules as a memory leak detection rule to the preset rule library.

[0212] In one possible implementation, the update module 1005 is further configured to: construct training samples based on code locations and their corresponding runtime data; and fine-tune the first neural network model using the training samples to update the first neural network model.

[0213] In one possible implementation, the monitoring module 1003 is specifically configured to monitor the memory dynamic behavior characteristics and resource consumption information of the code under test; wherein the memory dynamic behavior characteristics include at least one of memory snapshots, object lifecycle data, reference chain relationship graphs, and memory usage growth rate per unit time.

[0214] Figure 11 This is a schematic diagram of a computing device provided in an embodiment of this application.

[0215] like Figure 11As shown, the computing device 1100 includes a processor 1101 and a memory 1102. Exemplarily, the computing device 1100 may also include a communications interface 1103 and a communications bus 1104.

[0216] The processor 1101, memory 1102, and communication interface 1103 communicate with each other via communication bus 1104. The communication interface 1103 may include a transmitter and receiver for communicating with other devices or communication networks. It can be a wired interface (port), such as a fiber distributed data interface (FDDI) or a gigabit Ethernet interface (GE).

[0217] In some embodiments, the processor 1101 is used to execute program 1105, specifically performing the relevant steps in the above-described memory leak detection method embodiments. Specifically, program 1105 may include program code, which includes computer-executable instructions.

[0218] For example, processor 1101 may be a central processing unit (CPU), an application-specific integrated circuit (ASIC), or one or more integrated circuits configured to implement some embodiments of this application. Computing device 1110 may include one or more processors, which may be processors of the same type, such as one or more CPUs; or processors of different types, such as one or more CPUs and one or more ASICs. The CPU may be a single-core CPU or a multi-core CPU.

[0219] In some embodiments, memory 1102 is used to store program 1105. Memory 1102 may include high-speed random access memory (RAM) or non-volatile memory (NVM), such as at least one disk storage device.

[0220] Specifically, program 1105 can be called by processor 1101 to cause computing device 1100 to perform a memory leak detection method operation.

[0221] Some embodiments of this application provide a computer-readable storage medium storing at least one executable instruction that, when executed on a computing device 1100, causes the computing device 1100 to perform the memory leak detection method described in the above embodiments.

[0222] For example, the computer-readable storage medium can be a read-only memory (ROM), a random access memory (RAM), a compact disc read-only memory (CD-ROM), magnetic tape, a floppy disk, and an optical data storage device.

[0223] Some embodiments of this application provide a chip system applied to a server. The chip system includes one or more interface circuits and one or more processors. The interface circuits and processors are interconnected via lines. The interface circuits are used to receive signals from the server's memory and send signals to the processors, the signals including computer instructions stored in the memory. When the server processor executes the computer instructions, the server performs various steps in the inference task execution method shown in the above-described method embodiments.

[0224] The beneficial effects that the readable storage medium provided in some embodiments of this application can achieve can be referred to the beneficial effects in the corresponding inference task execution method provided above, and will not be repeated here.

[0225] It should be noted that, in this application, relational terms such as "first" and "second" are used merely to distinguish one entity or operation from another, and do not necessarily require or imply any such actual relationship or order between these entities or operations. Furthermore, the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, article, or apparatus. Without further limitations, an element defined by the phrase "comprising one..." does not exclude the presence of other identical elements in the process, method, article, or apparatus that includes the element.

[0226] The various embodiments in this specification are described in a related manner. Similar or identical parts between embodiments can be referred to mutually. Each embodiment focuses on describing the differences from other embodiments. In particular, the apparatus embodiments are basically similar to the method embodiments, so the description is relatively simple; relevant parts can be referred to the descriptions of the method embodiments.

[0227] The logic and / or steps represented in the flowchart or otherwise described herein, for example, can be considered as a sequenced list of executable instructions for implementing logical functions, and can be embodied in any computer-readable medium for use by, or in conjunction with, an instruction execution system, apparatus or device (such as a computer-based system, a processor-included system or other system that can fetch and execute instructions from, an instruction execution system, apparatus or device).

[0228] For the purposes of this specification, "computer-readable medium" can mean any means that can contain, store, communicate, propagate, or transmit programs for use by or in conjunction with an instruction execution system, apparatus, or device.

[0229] More specific examples of computer-readable media (a non-exhaustive list) include the following: electrical connections having one or more wires (electronic devices), portable computer disks (magnetic devices), random access memory (RAM), read-only memory (ROM), erasable and editable read-only memory (EPROM or flash memory), fiber optic devices, and portable optical disc read-only memory (CDROM).

[0230] Furthermore, the computer-readable medium can even be paper or other suitable media on which the program can be printed, because the program can be obtained electronically, for example, by optically scanning the paper or other medium, followed by editing, interpreting, or otherwise processing as necessary, and then stored in computer memory. It should be understood that various parts of this application can be implemented using hardware, software, firmware, or a combination thereof.

[0231] In the above embodiments, multiple steps or methods can be implemented using software or firmware stored in memory and executed by a suitable instruction execution system. For example, if implemented in hardware, as in another embodiment, it can be implemented using any one or a combination of the following techniques known in the art: discrete logic circuits having logic gates for implementing logical functions on data signals, application-specific integrated circuits (ASICs) having suitable combinational logic gates, programmable gate arrays (PGAs), field-programmable gate arrays (FPGAs), etc. The embodiments described above are merely specific embodiments of this application and are not intended to limit the scope of protection of this application. Any modifications, equivalent substitutions, improvements, etc., made based on the technical solutions of this application should be included within the scope of protection of this application.

Claims

1. A method for detecting memory leaks, characterized in that, include: Obtain the code to be tested; Using the code to be tested as input to the first neural network model, a parameterized test script for the code to be tested is generated using the first neural network model. Run the parameterized test script; During the execution of the parameterized test script, the runtime data of the code under test is monitored; In the event of a memory leak, the location of the code causing the memory leak in the code under test is determined based on the runtime data. Generate a leak detection report; the leak detection report includes the code location and the test execution path; wherein, the test execution path is used to characterize the execution trajectory from the starting position that triggers the execution of the code under test to the code location when the parameterized script is run.

2. The memory leak detection method according to claim 1, characterized in that, The process of obtaining the test code for memory leak detection includes: Obtain the first target code, which is any code segment in the source code; Based on the first target code and the preset memory leak feature pattern, determine the second target code in the first target code that meets the memory leak features; The second target code is parsed to generate a first target structure tree of the second target code; the first target structure tree is used to reflect the syntactic structure relationship of the second target code; The first target structure tree is matched with the structured memory leak detection rules in the preset rule base to obtain the code to be tested; the code to be tested is a code segment in the first target code that has a potential memory leak risk.

3. The memory leak detection method according to claim 1 or 2, characterized in that, In the event of a memory leak, determining the location of the code causing the memory leak in the code under test based on the runtime data includes: Based on the matching relationship between the runtime data and the preset exception judgment conditions, the third target code in the code to be tested is determined; Using the second target structure tree as input to the second neural network model, at least one code defect rule and at least one code location of the memory leak are obtained; wherein, the second target structure tree is used to characterize the structural relationship of the third target code.

4. The memory leak detection method according to claim 3, characterized in that, The step of determining the third target code in the code to be tested based on the matching relationship between the runtime data and the preset exception judgment conditions includes: Obtain at least two memory snapshots of the code under test during the execution of the parameterized test script; Comparative analysis of the at least two memory snapshots is performed to obtain at least one target object type; If the target object type satisfies the condition that the number of instances or the total memory usage increases monotonically between two snapshots, the target object type is determined to be an abnormal object type. Based on the creation location and / or reference holding path of at least one of the aforementioned exception object types, a third target code in the code to be tested is determined.

5. The memory leak detection method according to claim 3 or 4, characterized in that, Before obtaining the code to be tested, the process also includes: The method involves acquiring multiple original code features and corresponding repair methods for each feature; the original code features are used to characterize structured code fragments with preset memory leak feature patterns; the original code features include a first type of code features and a second type of code features; the first type of code features are structured code features extracted from known memory leak issues in open-source code repositories and vulnerability databases; the second type of code features are structured code patterns extracted from historical memory leak cases, which are determined based on runtime monitoring data. Based on the first type of code features, the second type of code features, and the preset rule template, the memory leak detection rules are generated; Multiple memory leak detection rules and multiple repair methods are stored in the preset rule base.

6. The method for detecting memory leaks according to any one of claims 3-5, characterized in that, After generating the leak detection report, it also includes: The multiple code defect rules are evaluated to obtain the evaluation results corresponding to each code defect rule; When the evaluation result meets the preset rule entry conditions, at least one of the multiple code defect rules is added to the preset rule library as the memory leak detection rule.

7. The memory leak detection method according to claim 1, characterized in that, After generating the leak detection report, the following is also included: Training samples are constructed based on the code location and the corresponding runtime data. The first neural network model is fine-tuned using the training samples to update the first neural network model.

8. The memory leak detection method according to claim 1, characterized in that, The monitoring of runtime data for the code under test includes: Monitor the memory dynamic behavior characteristics and resource consumption information of the code under test; wherein, the memory dynamic behavior characteristics include at least one of memory snapshots, object lifecycle data, reference chain relationship graphs, and memory usage growth rate per unit time.

9. A memory leak detection device, characterized in that, include: The static scanning engine is configured to retrieve the code to be tested. The intelligent generation module is configured to: use the code to be tested as input to a first neural network model, and use the first neural network model to determine the parameterized test script of the code to be tested; Monitoring module: configured to run the parameterized test script; The monitoring module is configured to monitor the runtime data of the code under test during the execution of the parameterized test script. The monitoring module is also configured to: in the event of a memory leak, determine the location of the code in the code under test that caused the memory leak based on the runtime data; The monitoring module is also configured to generate a leak detection report, which includes the code location and the test execution path. The test execution path is used to characterize the execution trajectory from the starting position that triggers the execution of the code under test to the code location when the parameterized script is run.

10. A computing device, characterized in that, The computing device includes a memory and a processor; the memory and the processor are coupled; the memory is used to store computer program code, the computer program code including computer instructions, which, when executed by the processor, cause the computing device to perform the memory leak detection method as described in any one of claims 1 to 8.