[C ++] dynamic memory allocation and memory leaks

Copyright: please indicate the source https://blog.csdn.net/weixin_40937100/article/details/88848886

Dynamic memory allocation


1. new and delete

函数原型:
void *operator new(size_t); //allocate an object
void *operator delete(void *); //free an object

1.1 new and delete operation mechanism (single object)

With class A for example:

class A
{
public:
    A(int v) : var(v){
        fopen_s(&file, "test", "r");
    }
    ~A(){
        fclose(file);
    }
private:
    int var;
    FILE *file;
};

When we create a pointer to an array of class A with new, new points to the memory space is returned pointer type A

class *pA = new A(10);

Behind the completion of the work is
Here Insert Picture Description
new work are the following:

  1. Due to the size of the A class is 8 Bytes (refer to "in-depth C ++ Object Model"), the new function will open up a 8 Bytes of address space, but the memory space is not initialized and typed
  2. Memory space to initialize class object. Call the constructor, to basic private variable assignment, the variable pointer pointing to the corresponding position
  3. Returns an object pointer

When we freed class object with delete

delete pA;

Behind the work is done:
Here Insert Picture Description
the Delete work are the following:

  1. Pointer pointing object calls the destructor for closing open files
  2. By calling the library function to delete freed memory space for the object, incoming parameter is a pointer pA, is the address of the object
1.2 with a new type [] and delete [] array of application and release

1. The application and release of an array of basic data types space
Here Insert Picture Description
Here Insert Picture Description
here will find, create different arrays and creating a single object, where new and delete becomes:
type * new type name = [];
delete [] name;

在上面的例子中,释放string类型数组空间时实际上先为10个string对象分别调用析构函数,再释放掉为10个string对象所分配的所有内存空间;而释放int类型数组空间时,因为int是内置类型不存在析构函数,所以直接释放掉了为10个int类型变量分配的所有空间。

因此,非内置类型数据用new type[] 来动态分配内存时,必须保存数据的维度,以确定在析构时需要调用对象析构函数的次数。C++的做法是在分配数组空间时在前面多分配了4 Bytes 大小的空间,专门保存数组的维度,在delete的时候根据数据维度调用析构函数,最后再释放所有内存空间。

以创建pA类对象数组为例说明 Type *name = new Type[] 和 delete[] name的运行机制
首先为对象数组分配内存空间:

class A *pAa = new A[3];

背后的工作是:
Here Insert Picture Description
当我们释放对象数组的内存空间时:

delete [] pAa;

背后的工作是:
Here Insert Picture Description
正如前面所说:依次为数组中每个对象调用析构函数,调用析构函数的总次数是由调用new库函数时开辟的内存空间的前4 Bytes 中保存的数据决定的;调用delete[] name 库函数时,其参数不是指针name的值(也是第一个数组元素的地址),而是这个地址值减去4 Bytes

1.3 内存泄漏

Here Insert Picture Description

2. malloc 和 free

  1. 头文件是#include<stdlib.h>,函数声明为:

void* malloc(size_t size);

  1. 参数size_t size表示动态内存分配空间的大小,以字节为单位。
  2. malloc()函数的返回值是一个指针,或者说是分配后内存空间的首地址.
  3. 如果malloc()函数申请空间成功则返回一段内存空间的首地址,失败则返回NULL
  4. 返回指针类型需要强制类型转换(有安全隐患)

int *p = (int *) malloc(sizeof(int));

  1. Before using the space malloc () function application, preferably with memset () function to clean up this memory space. The size of the malloc memory of the smart guarantee, there is no guarantee that garbage data
  2. malloc and free to be used in pairs, otherwise it will be a memory leak

Case:

//0.包含头文件<stdlib.h>
//1.定义一个char* 指针变量p,并分配10个字节内存空间(字符数组)
char *p = (char *)malloc(sizeof(char));

//2.将字符数组中的内容全部修改为0
memset(p, 0, 10 * sizeof(char));

//3.复制一段字符串到p指向的数组空间(长度要比所分配的内存小)
strcpy(p, "hello ");

//4.用realloc扩充p指向的内存空间
p = (char*)realloc(p, 20 * sizeof(char));

//4.在原字符串后面再拼接一段字符
strcat(p, "world");

//5.释放空间
free(p);


Difference 3.new/delete and malloc / free of

Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Other (duplicate mentioned above):

  1. new, delete C ++ is the operator (keyword), you can form expressions by specific syntax. malloc and free are standard library functions.
  2. is a library function malloc free, not an operator is not within the control range of the compiler, not automatically call the constructor and destructor. mallloc only variable is allocated memory, free memory just released variables.
  3. When new applications allocate memory space for the object, automatically call the constructor, but also can complete the initialization of the object. Similarly, delete may automatically call the destructor.
  4. new returns a pointer to the specified type, and may automatically calculate the size of the memory request; we need to calculate the malloc for memory size, and forcibly converted to the actual type of the pointer on return.
  5. new allocate memory from the free store; the malloc allocate memory from the heap.
  6. Compared with malloc, free, new, delete not only dynamically allocate memory space, and will call the constructor, destructor to initialize and destroy objects.

References:
C / C ++ - malloc and new new 10-point difference in C ++
C ++ reading notes -malloc () function, and attention point using the example

Guess you like

Origin blog.csdn.net/weixin_40937100/article/details/88848886