# 内存分配与释放

主要是来讲一讲new与malloc的区别

首先要注意，new和malloc可以用来申请自定义的变量的内存，也可以用来申请类的内存

那么类是有构造函数和析构函数的

使用new的话，会自动调用构造函数，delete时会自动调用析构函数

使用malloc的话，就不会自动调用构造函数，delete时也不会自动调用析构函数

```cpp
int *ptr = new int;//单个对象分配
int *ptr = new int[10];//数组对象分配

delete ptr;      // 释放单个对象
ptr = nullptr;   // 避免悬挂指针

delete[] ptr;    // 释放数组对象
ptr = nullptr;   // 避免悬挂指针
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tysun.gitbook.io/c++/nei-cun-fen-pei-yu-shi-fang.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
