Friends who are familiar with c should know that c provides programmers with the possibility of dealing with hardware, such as memory management. A high-level C programmer can optimize the performance of C programs to the extreme and drain hardware resources. And now I want to talk about new and malloc() related to memory management.
Let’s talk about malloc() first. Malloc is a function inherited from the C language. It is used to allocate a piece of memory. Its return result is a pointer to the memory you need. The pointer, its function prototype and usage examples are as follows:
/* 函数原型 其中__size是你要分配的大小,其单位是byte */ void* malloc(size_t __size); // 用例 int* pInt = (int*) malloc(sizeof(int)); // 分配了一个int double* pDoubleArray = (double*) malloc(sizeof(double) * 5); // 分配了一个double数组,其大小为5
Generally speaking, malloc can always allocate memory for you. But there are also situations where the situation is overwhelming and the memory is not enough. At this time, malloc will return a null pointer (NULL, nullptr). When you use malloc, you'd better check whether the returned pointer is null every time.
Related tutorials: C Video Tutorial
Now the memory has been allocated. When the program reaches a certain point, I don't want the memory anymore. At this time we need to manually release the memory, otherwise it will cause a memory leak. Free memory through the free() function. The function prototype and usage examples are as follows:
// 原型 void free(void* __ptr); // 用例 free(pInt); free(pDoubleArray);
What’s interesting is that what you pass to the free function is just a pointer, but whether you allocate an element or an array , free can always help you release this memory (how does free know the size of the array you allocated?)
Let me explain in detail what malloc does when allocating memory. When malloc allocates memory, it will not only allocate the memory size you need, it will also add some additional information to the head and tail of your memory (commonly known as cookie). For example, the information used for DEBUG and the size of your memory. This explains why it can free your memory, because it knows how big your memory is. It is worth mentioning that these cookies will take up some memory. . .
Okay, malloc has almost been introduced. Another thing I want to say is that malloc is only a third-party function, not a kernel function of the operating system. If you have additional needs, you can design your own malloc. Next let’s talk about new.
New is a manipulator (or keyword) provided by c. It is also used to allocate memory. Its use case is as follows:
int* pInt = new int(3); // 分配并构造一个int double* pDoubleArray = new double[5]; // 分配了一个double数组,其大小是5 delete pInt; // 删除单元素 delete[] pDoubleArray; // 删除数组
It’s still an old topic. Generally speaking, the program can allocate memory for you, but what should you do if you are really at the end of your rope? At this time, the program will throw a std::bad_alloc exception. Note that this is one of the differences between new and malloc. But what is commendable is that C provides a mechanism to handle bad_alloc exceptions. The method is as follows:
void BadAllocateHandler() { std::cout << "啊,内存分配失败了" << std::endl; exit(0); } std::set_new_handler(BadAllocateHandler);
BadAllocateHandler is a processing function written by the programmer himself when the allocation fails. And set_new_handler is a mechanism provided by c. Generally speaking, there are only two things you should do when the chips are down. Either let the program exit, or find a way to dig some memory elsewhere to continue allocation.
You already know that new is a keyword. For a program, all actions will return to function calls. So what exactly happened when new? When you create new, the program will first call the ::operator new() function. Then the program in ::operator new() will call malloc(). oh! Everything is clear. It turns out that the essence of new is to call the malloc function! ! In the same way, the essence of delete is to call the free() function.
Although the essence of new is to call malloc, there is one big difference between new and malloc. That is, after new comes out of the memory, new will help you construct the object, while malloc only allocates memory. The specific example is as follows:
class MyObj { public: public MyObj(int value) : val(value) {} int val; }; MyObj* obj = new MyObj(4); MyObj* obj1 = (MyObj*) malloc(sizeof(MyObj));
The method of new is that after malloc allocates the memory, the compiler will directly call the constructor of the class to construct the object in this memory. Notice! Only the compiler can directly call the constructor of a class. And if you use malloc, you can't construct objects directly on it.
The above is the detailed content of C++ learning new() and malloc() functions. For more information, please follow other related articles on the PHP Chinese website!

C++是一种广泛使用的面向对象的计算机编程语言,它支持您与之交互的大多数应用程序和网站。你需要编译器和集成开发环境来开发C++应用程序,既然你在这里,我猜你正在寻找一个。我们将在本文中介绍一些适用于Windows11的C++编译器的主要推荐。许多审查的编译器将主要用于C++,但也有许多通用编译器您可能想尝试。MinGW可以在Windows11上运行吗?在本文中,我们没有将MinGW作为独立编译器进行讨论,但如果讨论了某些IDE中的功能,并且是DevC++编译器的首选

在C++程序开发中,当我们声明了一个变量但是没有对其进行初始化,就会出现“变量未初始化”的报错。这种报错经常会让人感到很困惑和无从下手,因为这种错误并不像其他常见的语法错误那样具体,也不会给出特定的代码行数或者错误类型。因此,下面我们将详细介绍变量未初始化的问题,以及如何解决这个报错。一、什么是变量未初始化错误?变量未初始化是指在程序中声明了一个变量但是没有

C++是一门广受欢迎的编程语言,但是在使用过程中,经常会出现“未定义的引用”这个编译错误,给程序的开发带来了诸多麻烦。本篇文章将从出错原因和解决方法两个方面,探讨“未定义的引用”错误的解决方法。一、出错原因C++编译器在编译一个源文件时,会将它分为两个阶段:编译阶段和链接阶段。编译阶段将源文件中的源码转换为汇编代码,而链接阶段将不同的源文件合并为一个可执行文

如何优化C++开发中的文件读写性能在C++开发过程中,文件的读写操作是常见的任务之一。然而,由于文件读写是磁盘IO操作,相对于内存IO操作来说会更为耗时。为了提高程序的性能,我们需要优化文件读写操作。本文将介绍一些常见的优化技巧和建议,帮助开发者在C++文件读写过程中提高性能。使用合适的文件读写方式在C++中,文件读写可以通过多种方式实现,如C风格的文件IO

C++是一门强大的编程语言,它支持使用类模板来实现代码的复用,提高开发效率。但是在使用类模板时,可能会遭遇编译错误,其中一个比较常见的错误是“无法为类模板找到实例化”(error:cannotfindinstantiationofclasstemplate)。本文将介绍这个问题的原因以及如何解决。问题描述在使用类模板时,有时会遇到以下错误信息:e

iostream头文件包含了操作输入输出流的方法,比如读取一个文件,以流的方式读取;其作用是:让初学者有一个方便的命令行输入输出试验环境。iostream的设计初衷是提供一个可扩展的类型安全的IO机制。

c++初始化数组的方法:1、先定义数组再给数组赋值,语法“数据类型 数组名[length];数组名[下标]=值;”;2、定义数组时初始化数组,语法“数据类型 数组名[length]=[值列表]”。

C++是一种流行的编程语言,它强大而灵活,适用于各种应用程序开发。在使用C++开发应用程序时,经常需要处理各种信号。本文将介绍C++中的信号处理技巧,以帮助开发人员更好地掌握这一方面。一、信号处理的基本概念信号是一种软件中断,用于通知应用程序内部或外部事件。当特定事件发生时,操作系统会向应用程序发送信号,应用程序可以选择忽略或响应此信号。在C++中,信号可以


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)