C++ learning new() and malloc() functions

little bottle
Release: 2019-04-30 13:19:07
forward
3628 people have browsed it

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
Copy after login

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);
Copy after login

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;             // 删除数组
Copy after login

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);
Copy after login

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));
Copy after login

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!

Related labels:
c++
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!