[C/C++]_[初级]_[malloc-calloc-new的区别]

本文介绍了 C/C++ 中动态内存分配的三种方式:malloc、calloc 和 new 的区别。malloc 仅分配内存,返回无类型的指针,需要手动类型转换;calloc 类似于 malloc,但会将分配的内存初始化为零;new 是 C++ 特有的,它不仅分配内存,还根据指定类型调用构造函数,简化了使用并提供类型安全。new 在内存不足时可能抛出异常,而 malloc 返回 NULL。建议在 C++ 中使用 new 以获得更清洁、更安全的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


转载地址:  http://blog.lehu.shu.edu.cn/nyy_ww/A222351.html


Malloc
To use malloc, you must tell it how many bytes you want it to allocate. If you know the size of the datatype you want to create, multiply that by the number of cells you want in the array. However, most of the time you don’t know the size of the structure (or it is a pain in the butt to figure it out manually), so you should let the compiler figure it out for you. To do this, you must use the sizeof operator multiplied by the number of cells you want in the array. Malloc then returns a void pointer to the memory that it has just allocated on the heap.
array = (int*)malloc( sizeof(int) * 10 );
Look at the parameter of malloc first. You retrieve the size of an integer (which is usually four bytes, but some compilers use different-sized integers) and multiply that by 10. This should give you enough space for an array that will contain ten integers. Now, look in front of the malloc call; you see the int keyword followed by a pointer symbol, all within parentheses. This part is only needed if you are using C++. Remember, malloc returns a void pointer, which means that it has no type. C was lax and allowed you to implicitly cast the pointer into an integer pointer, but C++ doesn’t allow you to do that. Implicit conversion means that it will automatically convert the void pointer that malloc returns into an int pointer. C++ will complain about the line without that conversion. Now, if everything goes as planned, array should now point to a valid array. There is a chance that array doesn’t point to a new array, however. It might still be 0. If the amount of memory you ask for is not available, malloc returns 0. Now that you have your array, you can
use it exactly like you used the static array.


Calloc
Whenever you get memory from malloc, the memory you get is mostly junk. Most of the time you will have to manually reset the memory to the values you want. Usually the most popular initial value is 0. This is what calloc is for. Calloc is exactly like malloc, except that it goes one step further and resets every byte that it al locates to 0.
array = (int*)calloc( 10, sizeof(int) );
Note that calloc has 2 parameters instead of 1. Whereas malloc accepts the number of bytes you want to allocate as the only parameter, calloc wants the number of cells as the first parameter and the size of each cell in bytes as the second parameter.


 


New
C++ uses a different method of creating dynamic arrays, but the end result is the same. The new operator places all memory it allocates on the heap, just like malloc does. The new operator, however, doesn’t return a void pointer. Instead, it returns a pointer to whichever datatype you request from it, thus removing the requirement to cast the pointer to the appropriate datatype. The new operator also automatically determines the datatype’s size, so you don’t have to use the s izeof operator at all. Here’s an example of how to create a 10-cell integer array using new:
1: int* array = 0;
2: array = new int[10];
On line 1, I _declare the array just like I did before and set it to 0. On line 2, I tell new to give me an array with ten integers.


Unlike malloc, there is some confusion as to what happens when a call to new fails. Before the C++ standard was actually standardized, new used to act just like malloc when it failed and return 0. However, when exceptions (a new error-handling feature) were added to the C++ standard, new was changed to throw an exception whenever it failed. (See Appendix A, “A C++ Primer,” for more information about exceptions.) In the official standard, new throws an exception of type bad_alloc. However, most compilers just return 0 anyway and don’t throw the exception. This is because the makers of the compilers want to be able to let people compile code that was made prior to the standard. You should check your compiler documentation to determine which event happens. MSVC6 currently returns 0 whenever a call to new fails.


The new approach looks a lot cleaner than the malloc approach, and it’s generally more understandable. There is one major difference between this approach and malloc, however: malloc returns memory that will contain junk, but new executes the default constructor for each item in the array. (See Appendix A if you are unfamiliar with constructors.) In this example, both methods are the same because ints don’t have constructors and will contain junk no matter which method you use, but if you used new to create an array of classes, each class will be constructed properly.


This approach can either be a good thing or a bad thing, depending on how you use it. Logic tells us that if a constructor is called on every item, it will take longer to create the array, so malloc should be faster. However, constructors are meant to initialize a class so that it contains useful information. Most of the time, you’ll find yourself manually initializing your arrays after using malloc anyway, so the loss of speed from using new is usually minimal. Personally, I recommend using new over malloc because it is cleaner and safer.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值