C ++ new and delete and QT memory recovery mechanisms

Source: Internet
Author: User

In C ++ primer, we read that new is applying for a memory resource in the heap. New must be used in pairs with Delete. Otherwise, memory leakage may occur. You can learn QT recently, I often see the situation where only new is not deleted. Is this caused memory overflow? None? Baidu suddenly realized the memory management mechanism of QT. The original Article is as follows:

 

1. all classes inherited from the qobject class. If the father is specified during the new operation, the father is deleted when the father is deleted. Therefore, in a program, all qobject classes specify the parent, so they will be cleaned up at the top of the parent class without cleaning themselves;
2. the program usually has a root qobject at the top, that is, the qobject placed in setcentralwidget (). This qobject does not need to be specified as its father when it is new, because this statement sets its parent as the total qapplication, it is automatically cleared when the entire qapplication is not, so no cleaning is required. 9 here qt4 and qt3 are different. qt3 uses the setmainwidget function, but this function is not used as the father of qobject, so the top-level qobject in qt3 must be destroyed by itself ).
3. some may ask what will happen if I delete the pointers that QT takes over for destruction by myself? If so, under normal circumstances, the father of QT who owns this object will know about this matter, and it will directly Delete the son until it is deleted, so that it will remove the son from its list, and re-build the display content, but it is risky to directly do so! That is, the next
4. when a qobject is accepting the event queue, if you delete it halfway, it will be a problem. Therefore, we recommend that you do not delete a qobject directly in QT. If you do, to use the deletelater () function of qobject, it will clear the memory immediately after all events are handled, and there will be no problem even if the deletelater is called multiple times.
5. qt does not recommend holding a pointer to this qobject outside the parent range of a qobject, because if such a pointer is not noticed, the qobject will be released and an error will occur, to do this, remember where you did it, and then capture the destroyed () signal of the qobject that you used illegally, when it does not, quickly set your external pointer to zero. Of course, I think this is not in line with high-efficiency programming specifications, so if you want to hold a qobject pointer externally, we recommend that you use a reference or smart pointer, for example, QT provides smart pointers to address these situations. See the last article.
6. Smart pointers in QT are encapsulated as qpointer classes. All qobject subclasses can be packaged using this smart pointer. Many usage methods are the same as normal pointers. For details, see QT assistant.
By investigating the memory management function of QT, I found a lot of things. Now I think this QT is a little complicated, but it is very convenient to use, in the end, some memory leakage detection tools will think that the QT program has memory leakage in this way, so you don't have to worry about it when you discover it ~ ~

 

It turns out that QT has expanded the memory management mechanism of C ++. All new members of the class inherited from qobject will be automatically deleted, while manual delete will lead to unnecessary trouble.

 

In C ++, if you do not manually delete the object, will the new object occupy the memory all the time? None! After the process of the object ends, the system recycles all corresponding resources.

 

About Memory leakage (from Baidu encyclopedia)

Memory leakage explanation

Simply put, a memory space is applied for and is not released after use. Generally, the longer the program runs, the more memory it occupies, and the entire system crashes. A piece of memory applied by the program, and no pointer points to it, the memory will be leaked.

Edit the leakage category

Memory leakage can be classified as follows:

(1). Frequent Memory leakage.

Code with Memory leakage will be executed multiple times, resulting in a memory leak each time it is executed.

(2) Occasional Memory leakage.

Memory leakage occurs only in certain environments or operations. The frequency and frequency are relative. For a specific environment, unexpected events may become frequent. Therefore, the test environment and test method are crucial for detecting memory leaks.

(3) One-time memory leakage.

The code with Memory leakage is executed only once, or due to algorithm defects, there will always be only one piece of Memory leakage. For example, if the class constructor allocates memory but does not release the memory in the destructor, the memory leakage only occurs once.

(4) Implicit Memory leakage.

The program continuously allocates memory during the running process, but it does not release the memory until it ends. Strictly speaking, there is no memory leakage because the program releases all requested memory. However, if a server program needs to run for several days, weeks, or even months, failing to release the memory in time may eventually exhaust all the system memory. Therefore, we call this type of Memory leakage an implicit memory leak.

Edit this section hazards

From the perspective of user programs, memory leakage does not cause any harm. As a general user, the memory leakage does not exist. The real danger is the accumulation of Memory leakage, which will eventually consume all the memory of the system. From this point of view, one-time memory leakage is not harmful because it will not accumulate, while implicit memory leakage is very harmful, because it is more difficult to detect than frequent and occasional memory leaks.

Edit the memory leakage performance of this section

Memory leaks or, after resources are exhausted, what will the system show? Cpu resource depletion: it is estimated that the machine has no response, keyboard, mouse, and network. This is often seen on windows, especially in the form of viruses. Process id depletion: No way to create a new process, no way to create a serial port or telnet. Hard Disk depletion: The machine is dying, the swap memory is useless, and the log is useless. It is normal to die. Memory leakage or memory depletion: new connections cannot be created, and free memory is relatively small. There are many programs with memory leaks, but to have certain consequences, this process needs to be infinite loop and a service process. Of course, the kernel is also infinite loop, so if the kernel has a memory leak, the situation will be even worse. Memory leakage is a type of error that is difficult to locate and track. At present, there are no useful tools available (of course, there are some tools in the user space, including static analysis, it will also be dynamically analyzed, but there is no good open-source tool for finding the kernel memory leakage.) Memory leakage is closely related to the reference count of objects, in addition, c/c ++ does not have an automatic garbage collection mechanism. If the memory is not manually released, the problem will occur. To avoid this problem, we should start with the Code. Good coding habits and specifications can avoid errors. Generally, memory leakage refers to heap memory leakage. Heap memory refers to the memory allocated by the program from the heap, which is of any size (the size of the memory block can be determined during the running period). The released memory must be displayed after use. Applications generally use functions such as malloc, realloc, and new to allocate a block of memory from the heap. after use, the program must call free or delete to release the block. Otherwise, this memory cannot be used again, so we can say this memory is leaked.

Edit this memory leak detection tool

(Appendix) some memory leakage detection tools1. ccmalloc-simple memory leakage and malloc debugging libraries for C and C ++ programs in Linux and Solaris. 2. Dmalloc-Debug Malloc Library. 3. malloc () debugging Library written by Bruce Perens in Electric Fence-Linux distribution. 4. Leaky-programs for detecting memory leaks in Linux. 5. LeakTracer-Linux, Solaris, and HP-UX tracking and analysis of memory leaks in C ++ programs. 6. MEMWATCH-written by Johan Lindh, is an open-source C language memory error detection tool mainly through the gcc precessor. 7. valgrind-Debugging and profiling Linux programs, aiming at programs written in C and C ++. 8. KCachegrind-A visualization tool for the profiling data generated by Cachegrind and Calltree. 9.IBM Rational PurifyPlus-helps developers identify C/C ++ and hosting.. NET, Java, and VB6 code errors in performance and reliability. PurifyPlus combines features such as memory error and leak detection, Application Performance description, and code coverage analysis into a single and complete toolkit. 10. parasoft Insure ++-an automatic error detection tool for C/C ++ applications. It can automatically monitor C/C ++ programs, memory Corruption, memory leakage, pointer errors, and I/O errors are detected. By using a series of unique technologies (such as SCI technology and mutation testing), we thoroughly inspect and test our code, precisely locate the correct location of errors, and provide detailed diagnostic information. Can be used as a plug-in for Microsoft Visual C ++. 11. Compuware DevPartner for Visual C ++ BoundsChecker Suite-runtime error detection and debugging tool software designed for C ++ developers. Run as a plug-in for Microsoft Visual Studio and C ++ 6.0. 12. Electric Software GlowCode-including memory leakage check, code profiler, function call tracking, and other functions. Provides complete error diagnosis and runtime performance analysis toolkit for C ++ and. Net developers. 13. Compuware DevPartner Java Edition-includes Java memory detection, code coverage testing, code performance testing, thread deadlock, distributed applications, and other major functional modules. 14. Quest JProbe-analyzes Java Memory leakage. 15. ej-technologies JProfiler-a full-featured Java profiling tool dedicated to analyzing J2SE and J2EE applications. It combines CPU, thread, and memory analysis in a powerful application. 16. BEA JRockit-used to diagnose Java memory leaks and identify the root cause. It is specially designed for Intel platforms and optimized to achieve the highest performance on Intel hardware.

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.