In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the principle of memory management in C++". The content in the article is simple and clear, and it is easy to learn and understand. Now please follow the editor's train of thought slowly and deeply. Let's study and learn "what is the memory management principle of C++"?
1. The distribution of program memory in CumberCraft +.
The memory area of the program in CUniverse + is roughly divided into: kernel space (this part of the user can not read or write), stack, memory mapping segment, heap, data segment (storing global data, static data), code segment (storing executable code, read-only constants, also known as constant area).
1.1 memory distribution map
1.2 A small trial
Next, take a look at the following code and think about which memory area each variable is in.
Int globalVar = 1 * static int staticGlobalVar = 1 * * void test () {static int staticVar = 1; int localVar = 1; int num1 [10] = {1Mae 2, 3P 4}; char char2 [] = "abcd"; char * pchar3 = "abcd"; / / some compilers report errors and need to use const char int* ptr1 = (int*) malloc (sizeof (int) * 4)
The corresponding variable areas of the above code snippet are divided as follows:
2. Dynamic memory management in C language.
Let's review the previous dynamic memory management methods in C language: malloc / calloc/ realloc and free.
Read the following program paragraph with two questions:
What is the difference between 1.malloc / calloc/ realloc?
two。 Do you need free (p2) finally?
Void Test () {int* p1 = (int*) malloc (sizeof (int)); free (p1); int* p2 = (int*) calloc (4, sizeof (int)); int* p3 = (int*) realloc (p2, sizeof (int) * 10); free (p3);}
A:
1.calloc is equivalent to malloc+memset (0), that is, open space + initialization.
2.realloc is to expand the space of malloc/calloc, and the expansion involves two scenarios: in-situ expansion and remote expansion: in-situ expansion is the same as p3, or it may be remote expansion, so the space pointed to by p2 has been released, so in both cases we do not need to deal with p2.
3. Caching + memory management mode
In short, the memory management method of C language is relatively troublesome, so C++ proposed its own memory management method: dynamic memory management through new and delete operators.
3.1new/delete operation built-in type
1. Open up a single element
Free space syntax: delete name
Example:
Int* a = new int; / / dynamically apply for a space of type int and initialize it to 100delete a
two。 Open up n spaces of type type
Open up the basic syntax of n type types: type* name = new type [n]
Basic syntax for deletion: delete [] name
Example:
Int* ptr = new int [100]; / / dynamically apply for 100 spaces of int type delete [] ptr; / / pay attention! Be sure to match! Or you will fall apart!
3. For built-in types, there is really no difference between malloc/free and new/delete, and they serve exactly the same purpose.
Example:
Int main () {/ / malloc requests four integer sizes from memory int* p1 = (int*) malloc (sizeof (int) * 4); / / new requests four integer sizes from memory int* p2 = new int [4]; / / free frees up the space requested by p1 free (p1); p1 = nullptr / / delete frees up the space requested by p2 delete [] p2; return 0;}
3.2 new/delete operation custom type class Date {public: Date (int year=2021, int month=1, int day=1) {_ year= year; _ month= month; _ day= day;} private: int _ year; int _ month; int _ day;} Int main () {/ / malloc application for ten Date spaces Date* p1 = (Date*) malloc (sizeof (Date) * 10); free (p1); / / new application for ten Date spaces Date* p2 = new Date [10]; delete [] p2; return 0;}
Difference: when applying for a custom type space, new will call the constructor, delete will call the destructor, and mallo and free will not!
The underlying implementation principles of 4.new and delete (important implementation!)
Before explaining their underlying implementation principle, we need to introduce two global functions, namely operator new and operator delete.
New and delete are operators for dynamic memory request and release. Operator new and operator delete are global functions provided by the system. New calls the operator new global function at the bottom to apply for space, and delete calls the operator delete global function at the bottom to free space.
4.1operator new/operator delete
Operator new encapsulates two parts: malloc and failure throwing exception.
Here is the code for operator new:
Void* _ _ CRTDECL operator new (size_t size) _ THROW1 (_ STD bad_alloc) {/ / try to allocate size bytes void* p While ((p = malloc (size)) = = 0) / / if it is opened successfully, it will not enter the loop, and it can be clear that if (_ callnewh (size) = = 0) {/ / report no memory / / if the memory application fails An exception of bad_alloc type static const std::bad_alloc nomem will be thrown here _ RAISE (nomem);} return (p);}
Similarly, operator delete encapsulates free
Here is the code for operator delete:
Void operator delete (void* pUserData) {_ CrtMemBlockHeader* pHead; RTCCALLBACK (_ RTC_Free_hook, (pUserData, 0)); if (pUserData = = NULL) return; _ mlock (_ HEAP_LOCK); / * block other threads * / _ _ TRY / * get a pointer to memory block header * / pHead = pHdr (pUserData) / * verify block type * / _ ASSERTE (_ BLOCK_TYPE_IS_VALID (pHead- > nBlockUse)); _ free_dbg (pUserData, pHead- > nBlockUse); _ _ FINALLY _ munlock (_ HEAP_LOCK); / * release other threads * / _ _ END_TRY_FINALLY return;}
Summary: by observing the implementation of the above two global functions, it is not difficult to find that operator new actually applies for space through malloc. If malloc applies for space successfully, it will return directly, otherwise it will implement the measures to deal with the lack of space provided by users. If users provide this measure, continue to apply, otherwise, an exception will be thrown. Operator delete finally releases space through free.
Implementation principles of 4.2new and delete built-in types
There is no difference between malloc/free and new/delete in dealing with built-in types, except that a null pointer is returned when malloc fails to apply for space, while new throws an exception when applying for space, new/delete applies for and frees space for a single element, and new [] and delete [] apply for contiguous space.
Custom type
The principle of 1.new: 1. Call the operator new function to apply for space. two。 Execute the constructor on the application space to complete the initialization of the object.
The principle of 2.delete: 1. Execute the destructor in space to clean up the resources in the object. two。 Call the operator delete function to free up space.
In addition, the principle of new T [N]: call the operator new [] function, actually call the operator new function N times in operator new [] to complete the application of N object spaces, and then execute the N constructors on the applied space. The principle of * * delete []: * * perform N-th destructors on the released object space to clean up the resources in N objects. Then call operator delete [] to free up space, and actually call operator delete N times in operator delete [] to free up space.
Beginners may get confused when they see the part of "delete calls destructors to clean up object resources, and then calls operator delete function to free space". Here, take stack as an example:
Struct Stack {int* _ a; int _ top; int _ capacity; Stack (int capacity = 4): _ a (new int [capacity]), _ size (0), _ capacity (capacity) {cout
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.