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 只管分配内存,并不能对所得的内存进行初始化,所以得到的一片新内存中,其值将是随机的。 

 

MSND:

 

Allocates an array in memory with elements initialized to 0.
void *calloc(
   size_t num,
   size_t size
);


Parameters
num
Number of elements.
size
Length in bytes of each element.
Return Value
calloc returns a pointer to the allocated space. The storage space pointed to by the return value is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type other than void, use a type cast on the return value.
Remarks
The calloc function allocates storage space for an array of num elements, each of length size bytes. Each element is initialized to 0.
calloc calls malloc to use the C++ _set_new_mode function to set the new handler mode. The new handler mode indicates whether, on failure, malloc is to call the new handler routine as set by _set_new_handler. By default, malloc does not call the new handler routine on failure to allocate memory. You can override this default behavior so that, when calloc fails to allocate memory, malloc calls the new handler routine in the same way that the new operator does when it fails for the same reason. To override the default, call
_set_new_mode(1)
early in your program, or link with NEWMODE.OBJ.
When the application is linked with a debug version of the C run-time libraries, calloc resolves to _calloc_dbg. For more information about how the heap is managed during the debugging process, see The CRT Debug Heap.
Requirements
RoutineRequired headerCompatibility
calloc<stdlib.h> and <malloc.h>ANSI, Win 98, Win Me, Win NT, Win 2000, Win XP

For additional compatibility information, see Compatibility in the Introduction.
Libraries
All versions of the C run-time libraries.
Example
// crt_calloc.c
/* This program uses calloc to allocate space for
 * 40 long integers. It initializes each element to zero.
 */
#include <stdio.h>
#include <malloc.h>

int main( void )
{
   long *buffer;

   buffer = (long *)calloc( 40, sizeof( long ) );
   if( buffer != NULL )
      printf( "Allocated 40 long integers/n" );
   else
      printf( "Can't allocate memory/n" );
   free( buffer );
}
Output
Allocated 40 long integers

### 关于 `calloc` 分配内存失败的原因及解决方法 `calloc` 是 C 语言中用于动态分配内存的函数,其原型为 `void* calloc(size_t num, size_t size)`。它会分配一块连续的内存空间,并将其初始化为零[^1]。如果 `calloc` 分配内存失败,通常会返回 `NULL`,这可能由以下原因引起: #### 1. 内存不足 当系统可用的物理内存或虚拟内存不足以满足分配请求时,`calloc` 会返回 `NULL`。这种情况通常发生在尝试分配非常大的内存块时[^2]。 ```c void* ptr = calloc(1000000000, sizeof(int)); if (ptr == NULL) { // 内存分配失败处理逻辑 } ``` #### 2. 参数错误 如果传递给 `calloc` 的参数 `num` 或 `size` 超出了系统的限制(例如乘积超过 `SIZE_MAX`),则可能导致分配失败。此外,某些实现可能会检查参数的有效性,若发现无效值也会导致失败[^3]。 ```c size_t num = SIZE_MAX / sizeof(int) + 1; void* ptr = calloc(num, sizeof(int)); if (ptr == NULL) { // 参数可能导致溢出 } ``` #### 3. 系统限制 操作系统对每个进程可使用的最大内存大小有严格的限制。如果当前进程已经接近该限制,即使系统还有足够的空闲内存,`calloc` 也可能失败[^4]。 ```c // 检查系统资源限制 struct rlimit rl; getrlimit(RLIMIT_AS, &rl); printf("Max virtual memory: %lu bytes\n", rl.rlim_max); ``` #### 解决方法 - **检查返回值**:始终检查 `calloc` 的返回值是否为 `NULL`,并在失败时采取适当的措施。 - **减少分配量**:如果分配失败,可以尝试减少请求的内存大小,分多次分配。 - **优化内存使用**:确保程序没有内存泄漏或不必要的大内存占用。 - **增加系统资源**:在可能的情况下,增加物理内存或调整操作系统的资源限制。 ```c void* ptr = calloc(num, size); if (ptr == NULL) { fprintf(stderr, "Memory allocation failed\n"); exit(EXIT_FAILURE); } ``` ### 示例代码 以下是一个完整的示例,演示如何安全地使用 `calloc` 并处理可能的失败情况: ```c #include <stdio.h> #include <stdlib.h> int main() { size_t num = 1000000000; size_t size = sizeof(int); // 防止乘法溢出 if (num > 0 && size > 0 && num > SIZE_MAX / size) { fprintf(stderr, "Allocation request too large\n"); return EXIT_FAILURE; } void* ptr = calloc(num, size); if (ptr == NULL) { fprintf(stderr, "Failed to allocate memory\n"); return EXIT_FAILURE; } // 使用分配的内存... free(ptr); // 释放内存 return EXIT_SUCCESS; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值