search
HomeBackend DevelopmentC#.Net TutorialC++ 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!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools