C++ learning new() and malloc() functions
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Executing code in VS Code only takes six steps: 1. Open the project; 2. Create and write the code file; 3. Open the terminal; 4. Navigate to the project directory; 5. Execute the code with the appropriate commands; 6. View the output.
