您的位置:首页 > 其它

C 语言中 malloc、calloc、realloc 和free 函数的使用方法

2016-07-29 19:13 821 查看
C标准函数库中,常见的堆上内存管理函数有malloc(), calloc(), recalloc(), free()。

之所以使用堆,是因为栈只能用来保存临时变量、局部变量和函数参数。在函数返回时,自动释放所占用的存储空间。而堆上的内存空间不会自动释放,直到调用free()函数,才会释放堆上的存储空间。

一、具体使用方法

1、malloc()

头文件:stdlib.h

声明:void * malloc(int n);

含义:在堆上,分配n个字节,并返回void指针类型。

返回值:分配内存成功,返回分配的堆上存储空间的首地址;否则,返回NULL

2、calloc()

头文件:stdlib.h

声明:void *calloc(int n, int size);

含义:在堆上,分配n*size个字节,并初始化为0,返回void* 类型

返回值:同malloc() 函数

3、recalloc()

头文件:stdlib.h

声明:void * realloc(void * p,int n);

含义:重新分配堆上的void指针p所指的空间为n个字节,同时会复制原有内容到新分配的堆上存储空间。注意,若原来的void指针p在堆上的空间不大于n个字节,则保持不变。

返回值:同malloc() 函数

4、free()

头文件:stdlib.h

声明:void free (void * p);

含义:释放void指针p所指的堆上的空间。

返回值:无

5、memset()

头文件:string.h

声明:void * memset (void * p, int c, int n) ;

含义:对于void指针p为首地址的n个字节,将其中的每个字节设置为c。

返回值:返回指向存储区域 p 的void类型指针。

二、示例代码

/*
*  Author: klchang
*  Description:
Test the memory management functions in heap.
*  Created date: 2016.7.29
*/

#include <stdio.h>  // scanf, printf
#include <stdlib.h> // malloc, calloc, realloc, free
#include <string.h> // memset

#define SIZE 10

// Input Module
int* inputModule(int* ptrCount)
{
int* arr, d, i = 0;
int length = SIZE;

// Apply malloc()
arr = (int*)malloc(SIZE * sizeof(int));
memset(arr, 0, length * sizeof(int));

// Input module
printf("Input numbers until you input zero: \n");
while (1) {
scanf("%d", &d);
// count
*ptrCount += 1;
if (0 == d) {
arr[i] = 0;
break;
} else {
arr[i++] = d;
}
if (i >= length) {
// Apply realloc()
realloc(arr, 2*length*sizeof(int));
memset(arr+length, 0, length * sizeof(int));
length *= 2;
}
}

return arr;
}

// Output module
void outputModule(int* arr, int* ptrCount)
{
int i;

printf("\nOutput all elements that have been input: \n");
for(i = 0; i < *ptrCount; i++) {
if (i && i%5 == 0)
printf("\n");
printf("\t%d", *(arr+i));
}

// Release heap memory space
free(ptrCount);
free(arr);
}

int main()
{
int i = 0;
int* ptrCount;
int* arr;

// Apply calloc()
ptrCount = (int *)calloc(1, sizeof(int));
// Input Module
arr = inputModule(ptrCount);
// Before free() function, output the count of input numbers
printf("\n\nBefore using free() function, Count: %d", *ptrCount);
// Output Module
outputModule(arr, ptrCount);
// After free() function, output the count of input numbers
printf("\n\nAfter using free() function, Count: %d", *ptrCount);

return 0;
}


结果图片



参考资料:

1、C中堆管理——浅谈malloc,calloc,realloc函数之间的区别
http://www.cppblog.com/sandywin/archive/2011/09/14/155746.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: