About memory leaks in C + +

Source: Internet
Author: User

1.c++ memory leak definition: Memory leak leak refers to a situation in which a program fails to release memory that is no longer in use due to negligence or error. A memory leak does not mean that there is physical disappearance, but that the application allocates some memory, and because of the design error, it loses the control of the memory, thus causing the memory waste. 2. The consequences of memory leaks: one of the most elusive and hardest-to-detect errors is a memory leak, which is a bug that failed to properly release previously allocated memory. A small memory leak that occurs only once may not be noticed, but a program that leaks large amounts of memory or leaks an increasing number of programs may exhibit a variety of symptoms: from degraded performance to completely exhausted memory. Worse, a leaking program might use too much memory, causing another program to fail, leaving the user unable to find the real source of the problem. In addition, even harmless memory leaks can cause a variety of problems that can lead to a system crash. 3. The main concerns are two types of memory leaks: (1) heap memory leaks (heap leak). Memory refers to the allocation of a piece of memory from the heap by Malloc,realloc, new, etc., as required by the program running, and must be deleted by calling the corresponding free or delete after completion. If the program's design errors cause this part of the memory to not be released, then this memory will not be used, resulting in heap Leak. (2) system resource leakage (Resource Leak). Mainly refers to the program using the system allocation of resources such as bitmap,handle, socket and so does not use the corresponding function to release, resulting in system resources waste, serious can lead to lower system performance, system operation is not stable. 4. Methods for detecting memory leaks: (1) Debug running the debug version of the program, using the following technologies: CRT (C run-time Libraries) ( _CrtDumpMemoryLeaks()), run-time function call stack, memory allocation sequence prompt when memory leaks (Integrated development Environment Output window), comprehensive analysis of causes of memory leaks, and exclusion of memory leaks. (2) Run the time with Valgrind run, you can check the running time of the memory leak. Reference: how does C + + detect memory leaks and locate memory leaks? (know) How to detect memory leaks without tools in C + +? The following will cause a memory leak, which requires either free or delete.
#define _CRTDBG_MAP_ALLOC#include <stdlib.h>#include <crtdbg.h>#include <iostream>using namespace std;void GetMemory(char *p, int num){    p = (char*)malloc(sizeof(char)* num);    //free(p);    //delete p;}int main(int argc, char** argv){    char *str = NULL;    GetMemory(str, 100);    cout << "Memory leak test!" << endl;    _CrtDumpMemoryLeaks(); //检测内存泄露    return 0;}

Running the above code will present the detection information (a memory leak occurs at this time):

Detected memory leaks!Dumping objects ->c:\users\lzyrapx\documents\visual studio 2013\projects\test\test\test.cpp(9) : {145} normal block at 0x00D79F18, 100 bytes long. Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD Object dump complete.
5. Ways to prevent memory leaks: the most effective way to resolve a memory leak is to use smart pointers (smart Pointer). You don't have to worry about this with smart pointers, because smart pointers can automatically delete allocated memory. Smart pointers are similar to normal pointers, except that you do not need to manually release pointers, but instead manage the release of memory through smart pointers, so you don't have to worry about memory leaks. C + + provides smart pointers for auto_ptr, Unique_ptr, shared_ptr, and weak_ptr (Auto_ptr is the solution provided by c++98, C+11 has abandoned it and provided two other solutions). Smart pointer Pre-knowledge: (1) shared_ptr is a shared smart pointer: shared_ptr uses a reference count, and each shared_ptr copy points to the same memory. The memory is freed when the last shared_ptr is destroyed. Precautions: 1. Do not initialize multiple shared_ptr with a raw pointer. 2. Do not create shared_ptr in the function argument, define and initialize it before calling the function. 3. Do not return the this pointer as shared_ptr. 4. To avoid circular references. (2) Unique_ptr exclusive smart pointer: <1>unique_ptr is an exclusive smart pointer that does not allow other smart pointers to share their internal pointers, and is not allowed to assign one unique_ptr to another unique_ptr by assigning a value. <2>unique_pt R does not allow copying, but it can be returned to other unique_ptr through a function, and can also be transferred to other unique_ptr by Std::move, so that it no longer owns the original pointer. <3> If you want only one smart pointer to manage resources or manage arrays, use UNIQUE_PTR if you want multiple smart pointers to manage the same resource with shared_ptr. (3) weak_ptr Weak reference smart pointer: Weak reference smart pointer weak_ptr is used to monitor shared_ptr, does not make reference count plus one, it does not manage shared_ptr internal pointers, mainly to monitor the shared_ptr life cycle, More like an assistant to shared_ptr. WEAK_PTR does not overload operators * and-&gt, because it does not share pointers, it cannot manipulate resources, mainly to gain the monitoring power of resources through SHARED_PTR, its construction does not increase the reference count, its destruction does not reduce the reference count, Purely as a bystander to monitor the existence of shared_ptr-related resources. WeAk_ptr can also be used to return the this pointer and solve the problem of circular references. 7. Wild pointer Wild pointer: Pointer to the released or access limited memory. Causes of wild pointers: 1. The pointer variable is not initialized (it can be initialized to null if the value is indeterminate) 2. After the pointer is free or delete, it is not set to NULL, and only the memory that the pointer is pointing to is freed, and the pointer itself is not killed. At this point the pointer is pointing to "junk" memory. The released pointer should be set to NULL.3. The pointer operation goes beyond the scope of the variable, such as a pointer to the stack memory is the wild pointer.

About memory leaks in C + +

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.