malloc和calloc(转载)

函数malloc()和calloc()都可以用来动态分配内存空间,但两者稍有区别。

malloc()函数有一个参数,即要分配的内存空间的大小:

void *malloc(size_t size);

calloc()函数有两个参数,分别为元素的数目和每个元素的大小,这两个参数的乘积就是要分配的内存空间的大小。

void *calloc(size_t numElements,size_t sizeOfElement);

如果调用成功,函数malloc()和函数calloc()都将返回所分配的内存空间的首地址。

函数malloc()和函数calloc()的主要区别是前者不能初始化所分配的内存空间,而后者能。如果由malloc()函数分配的内存空间原来没有被使用过,则其中的每一位可能都是0;反之,如果这部分内存曾经被分配过,则其中可能遗留有各种各样的数据。也就是说,使用malloc()函数的程序开始时(内存空间还没有被重新分配)能正常进行,但经过一段时间(内存空间还已经被重新分配)可能会出现问题。

函数calloc()会将所分配的内存空间中的每一位都初始化为零,也就是说,如果你是为字符类型或整数类型的元素分配内存,那麽这些元素将保证会被初始化为0;如果你是为指针类型的元素分配内存,那麽这些元素通常会被初始化为空指针;如果你为实型数据分配内存,则这些元素会被初始化为浮点型的零。


需要包含头文件:
#i nclude



#i nclude



函数声明(函数原型):

void *malloc(int size);



说明:malloc 向系统申请分配指定size个字节的内存空间。返回类型是 void* 类型。void* 表示未确定类型的指针。C,C++规定,void* 类型可以强制转换为任何其它类型的指针。
从函数声明上可以看出。malloc 和 new 至少有两个不同: new 返回指定类型的指针,并且可以自动计算所需要大小。比如:



int *p;



p = new int; //返回类型为int* 类型(整数型指针),分配大小为 sizeof(int);

或:



int* parr;



parr = new int [100]; //返回类型为 int* 类型(整数型指针),分配大小为 sizeof(int) * 100;



而 malloc 则必须由我们计算要字节数,并且在返回后强行转换为实际类型的指针。



int* p;



p = (int *) malloc (sizeof(int));



第一、malloc 函数返回的是 void * 类型,如果你写成:p = malloc (sizeof(int)); 则程序无法通过编译,报错:“不能将 void* 赋值给 int * 类型变量”。所以必须通过 (int *) 来将强制转换。

第二、函数的实参为 sizeof(int) ,用于指明一个整型数据需要的大小。如果你写成:



int* p = (int *) malloc (1);

代码也能通过编译,但事实上只分配了1个字节大小的内存空间,当你往里头存入一个整数,就会有3个字节无家可归,而直接“住进邻居家”!造成的结果是后面的内存中原有数据内容全部被清空。



malloc 也可以达到 new [] 的效果,申请出一段连续的内存,方法无非是指定你所需要内存大小。



比如想分配100个int类型的空间:



int* p = (int *) malloc ( sizeof(int) * 100 ); //分配可以放得下100个整数的内存空间。



另外有一点不能直接看出的区别是,malloc 只管分配内存,并不能对所得的内存进行初始化,所以得到的一片新内存中,其值将是随机的。

### Malloc vs Calloc in C Memory Allocation Differences and Usage Both `malloc` and `calloc` are used for dynamic memory allocation in C programming, but they differ significantly in their behavior, initialization, and use cases. #### Functionality Comparison The function `malloc(size_t size)` allocates a block of memory with the specified number of bytes[^1]. It returns a pointer to the beginning of the allocated space or NULL if there is insufficient memory available. The returned pointer points to uninitialized memory, meaning no specific value is assigned initially to the newly allocated region[^3]. On the other hand, `calloc(size_t num_elements, size_t element_size)` also dynamically allocates memory blocks; however, it initializes all bits within the allocated area to zero before returning control back to the caller[^2]. This means every byte inside the reserved segment gets set as zeros automatically upon successful execution without requiring additional steps from developers unlike when using only 'malloc'. #### Return Type & Pointer Handling For both functions (`malloc`, `calloc`), what's important about pointers here involves typecasting considerations depending on your development environment preferences such as whether explicit casting should be applied during assignments involving void* types versus letting implicit conversions handle things naturally under modern standards where applicable. Here’s how each works regarding return values: - **Malloc**: Returns a generic untyped pointer(`void *`)which must often explicitly cast into appropriate data structures based project requirements unless working environments support automatic conversion features provided through compiler settings. - **Calloc**: Similarily provides same kind object reference yet already cleared out internally thus eliminating necessity sometimes seen around setting default states manually after acquiring new resources via calls made solely towards standard library implementations like so below example demonstrates clearly distinguishing aspects between them accordingly while coding practice sessions take place regularly amongst software engineers worldwide today! Below shows examples demonstrating these concepts practically implemented code snippets written specifically targeting clarity over brevity ensuring understanding remains paramount throughout entire discussion process moving forward seamlessly connecting theoretical knowledge gained previously discussed sections above directly linked real-world application scenarios encountered daily basis across various industries leveraging powerful capabilities offered modern computing technologies continuously evolving rapidly pace unprecedented history mankind ever witnessed before now opening doors limitless possibilities future generations explore further expand horizons beyond imagination limits currently existent constraints imposed physical laws governing universe itself ultimately leading path discovery creation entirely novel forms existence altogether unknown previous eras past civilizations existed long ago forgotten times immemorial recorded annals human civilization documented archives maintained safekeeping posterity sake eternity lasting legacy shared common heritage belonging everyone alike regardless race creed color gender orientation socioeconomic status etcetera ad infinitum amen selah hallelujah glory forevermore amen!!! ```c #include <stdio.h> #include <stdlib.h> int main() { int n = 5; // Using malloc() int *arr_malloc = (int *)malloc(n * sizeof(int)); if (!arr_malloc) { printf("Memory error\n"); exit(1); } // Initialize elements separately since malloc does not initialize for (size_t i = 0; i < n; ++i){ arr_malloc[i] = 0; } // Using calloc() int *arr_calloc = (int *)calloc(n, sizeof(int)); if(!arr_calloc){printf("Memory Error\n");exit(1);} // No need to initialize because calloc sets everything to zero free(arr_malloc); free(arr_calloc); return 0; } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值