C ++ new, delete and dynamic memory

Dynamic memory = smart pointer + direct management (new delete)

Why use dynamic memory?

  1. The program does not know how many objects need to be used
  2. I don't know the type of object needed
  3. Need to share data among multiple objects

C ++ memory classification: stack area, heap area, global area (static area), constant area, code area
static stack, local variable
dynamic heap, new malloc

1. Four smart pointers of c ++: (header memory)

auto_ptr is deprecated and replaced by unique_ptr!
shared_ptr allows multiple pointers to point to the same object. Two objects use a
shared_ptr member variable to point to each other, causing circular references, invalidating the reference count, and memory leaks. Implement the concept of shared ownership. Multiple smart pointers can point to the same object. The object and its related resources will release the
make_shared function when "the last reference is destroyed" , which is the safest way to allocate and use dynamic memory.

make_shared在动态内存中分配一个对象并初始化,返回指向该对象的shared_ptr。
shared_ptr<int> p=make_shared<int>(0)//指向值为0的int的shared_ptr
auto q(p);//用p来初始化q,两个指向相同对象。。引用计数加一!!!
q.use_count()//计数
auto r=make_shared<int>(43);
r=s;//r原来指向的对象没有引用者,会调用析构函数,销毁对象。释放内存!!!
shared_ptr<int> p1(new int(1024));//shared_ptr用new初始化
p1.reset//释放

unique_ptrr "unique" owns the object it refers to, and only one unique_ptr can point to the given object at the same time (other pointers want to point to this object, first release !!!). Avoid resource leaks

unique_ptr<int> u1 (new int(1024));//不支持拷贝和赋值
u1=nullptr;//释放u指向的对象,将u置空
u1.reset();//释放u指向的对象
u1.release();//u放弃原指针的控制权,将u置空。返回指针,返回指针,返回指针!!!!
unique_ptr<int> p2(p1.release());//将所有权从p1转移给p2

weak_ptr solves the memory leak caused by circular references. Points to the object managed by shared_ptr, but does not increase use_count ().

auto p=make_shared<int>(42);
weak_ptr<int>wq(p);//wq弱共享p。

The role of
smart pointers : The role of smart pointers is to manage a pointer. The applied space is forgotten to be released at the end of the function, which will cause a memory leak. Using smart pointers can be avoided. A smart pointer is a class. When it exceeds the scope of the class, the class will automatically call the destructor to release resources.

2, new, new [] and malloc

Differences:
When the basic type of array elements in new [], the array space can be released through both delete and delete [];
when the array element in new [] is a custom type, the array can only be released through delete [] space.
When Yuan Shu in the array is of a custom type, delete will only call the destructor of the first element in the array when releasing space,
and delete [] will call the destructor of all elements in the array when releasing space.
The new / delete malloc / free
keyword can overload library functions.
Call the constructor / destructor. Object + memory memory
returns a pointer to the object returns void *, and it also needs to be forced to
automatically allocate memory according to the data type. The size specified during the application can be reallocated and expanded.
If the allocation fails, return bad_malloc. Try to catch. If the allocation fails, return NULL. The
difference between malloc and new:
1. new / delete is a C ++ keyword and needs compiler support. New will call the constructor, you cannot specify the memory size, and the returned pointer does not need to be forced. In addition to internal data types, dynamic objects are also supported. Object + memory, returns a pointer to the object. If new fails, a badallloc exception is returned. Nothrow does not throw an exception.
2. malloc needs to specify the size of the application memory, and the returned pointer needs to be forced. . malloc / free is a library function and requires header file support. Only internal data types are supported. RAM. Return void *

int *arr=int*malloc(sizeof(int)*n)
free(arr);
//如果new失败,返回一个bad_alloc类型的异常
int *pi=new int(1024);//pi指向对象的值为1024
string *ps=new string//string初始化为空了
auto p1=new auto(obj);//obj是int,那么p1就是int*了
const int *p=new const int(1024);
delete p;//销毁对象 释放内存。所以p必须是对象或空指针
动态数组(不建议用,还是建议用标准容器)
int *p=new int[40];//表示有40个int
int *p1=new int[40]()//初始化为0了
delete []p;//逆序先销毁最后一个,,,直到第一个元素
智能指针unique_ptr可以管理动态数组new[]
unique_ptr<int[]> p(new int[10]);
p.release();//自动调用delete[]
allocator类
allocator<string>alloc;
auto const p=alloc.allocate(n);//分配n个未初始化的string
alloc.deallocate(p,n)//释放p指向的那块内存
alloc.desdoy(p);//调用析构函数,销毁p指向的对象

auto q=p;//q指向最后一个元素位置
alloc.construct(q++,"hello");//初始化构造的对象
while(q!=p)
    alloc.destroy(--q);//销毁对象(必须是先构造的元素)

3. The principle of malloc. brk and mmap system calls?

In order to reduce the memory fragmentation and system call overhead, malloc uses the memory pool method, first apply for a large block of memory as the heap area, and then divide the heap into multiple memory blocks (blocks are the basic unit of memory management). , Allocate a suitable free block directly from the heap area. malloc divides the heap into consecutive, different-sized blocks (allocated blocks and free blocks), and then connects the free blocks with a doubly linked list.
When users apply for memory, malloc facilitates all free blocks and then allocates blocks of appropriate size. . . (When merging memory, malloc uses boundary notation and decides whether to merge based on whether the blocks before and after each block are allocated.)
Malloc generally uses brk or mmap system calls when applying for memory. When the application memory is less than 128k, the system function brk will be used to allocate in the heap area. When it is greater than 128k, use mmap to allocate in the mapping area.

4. Wild pointer and dangling pointer

The dangling pointer is such a pointer: it used to point to a valid address, but now it no longer points to a valid address (personally added, in fact, the original address can not be accessed through this pointer area). This is usually because the memory unit pointed to by the pointer is released and is no longer valid. There is no problem with a dangling pointer, unless you try to access the address space pointed to by this pointer. It is always best practice not to leave any dangling pointers.

#include <stdlib.h>
void func(){
    char *dp = (char *)malloc(A_CONST);
    free(dp);         //dp变成一个空悬指针
    dp = nullptr;        //dp不再是空悬指针
}

The above example reminds us that when free or delete is called, in addition to freeing dynamically applied memory, the related pointer must also be pointed to NULL to avoid a dangling pointer.

A wild pointer is a pointer that is not properly initialized and points to a random memory address. The existence of a wild pointer is a serious mistake.

Wild pointer: The wild pointer points to a random memory space and is not controlled by the program.
If it is not initialized or points to a memory space that does not have access rights, problems will arise if it is later dereferenced.

Causes of wild pointer
1. The pointer variable is not initialized. When any pointer variable is first created, it will not automatically become a NULL pointer. Its default value is random, and it will be irritated.
2. After the pointer p is free or deleted, it is not set to NULL, which makes people mistakenly believe that p is a legal pointer. // This is the empty dangling pointer
3. The pointer operation exceeds the scope of the variable. This situation is unpredictable.

5. Memory leak

Definition: A memory leak refers to a program that fails to free memory that is no longer in use due to negligence or error.
Memory overflow: The memory space used exceeds the system allocation
Consequences: poor performance, memory exhaustion
Common types:
heap memory leaks: malloc, new, and realloc are used. Useless free and delete release
System resource leak: the resources allocated to the program are not released using the corresponding function, such as bitmap \ handle \ socket. If the
base class destructor is not a virtual function, the base class will not be called when it points to a subclass object Subclass destructor, causing memory leak.
Troubleshooting: BoundsChecker, locate various errors that occur during runtime,
debug and run the DEBUG version of the program, using the following technologies: CRT (C run-time libraries), runtime function call stack, memory allocation serial number prompted when a memory leaks (integrated development environment OUTPUT Window), comprehensive analysis of the causes of memory leaks, eliminate memory leaks.
Linux tool for detecting memory leaks-valgrind
windows uses CRT library functions to detect
mtrace to track and detect malloc. Or manually add the statistics function of memory application and release to see if they are consistent to determine the leak

Solution: Using a smart pointer, initialized to null
memory overflow out of memory, means that when the program applies for memory, there is not enough memory space for it to use, and out of memory appears; for example, an integer is applied, but long ability is stored for it The number saved is a memory overflow.

Published 19 original articles · Like9 · Visits 2900

Guess you like

Origin blog.csdn.net/u013031697/article/details/104824662