您的位置:首页 > 编程语言 > C语言/C++

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

2015-06-15 10:11 597 查看
转载地址: 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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: