一、前言
本文将介绍如何动态分配存储空间,重点介绍c标准中动态分配存储空间的函数:malloc、calloc、realloc,以及使用alloc的注意事项,最后将介绍alloc类函数的替代接口。
二、malloc
相信大家对malloc函数并不陌生,malloc用于分配指定字节数的存储区,此存储区中的初始值是不确定的。
头文件:stdlib.h 函数原型:void* malloc(size_t size)
传入参数:所需申请的字节数
返回值:指向申请到的内存块的指针,如果分配失败,返回NULL
参考代码如下:
/*************************************************************************
> File Name: alloc_like_test.c
> Author: conbiao
> Created Time: 2024年09月11日 星期三 14时02分16秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
/************************************************************************
* MACRO
************************************************************************/
#define RING_BUFFER_SIZE 20
/************************************************************************
* MAIN
************************************************************************/
int main(int argc, char *argv[])
{
int *ring_buffer = NULL;
int *buffer_prt = NULL;
int i = 0;
int num = 0;
ring_buffer = malloc(sizeof(int) * RING_BUFFER_SIZE);
if(!ring_buffer)
{
printf("%s: malloc failed!\n",__func__);
return -1;
}
buffer_prt = ring_buffer;
while(1)
{
if(num == 65536)
{
num = 0;
}
if(i == RING_BUFFER_SIZE - 1)
{
printf("%s: arrive the end of buffer,start from the begin!\n",__func__);
*buffer_prt = num;
buffer_prt = ring_buffer;
i = 0;
}
else
{
*buffer_prt = num;
buffer_prt++;
i++;
}
num++;
for(int j = 0; j < RING_BUFFER_SIZE - 1; j++)
{
printf("%s: ring_buffer[%d] = %d\n",__func__,j,ring_buffer[j]);
}
}
free(ring_buffer);
return 0;
}
上面的代码动态申请了一段20个int型大小的内存,作为一个环形buffer一直往里面填数据,运行结果如下:
(2-1)
三、calloc
calloc为指定数量和大小的内存块分配空间,并将其初始化为0.
头文件:stdlib.h 函数原型:void* calloc(size_t num, size_t size);
传入参数: num:数量
size:大小 返回值:指向申请到的内存块的指针,如果分配失败,返回NULL
参考代码如下:
/*************************************************************************
> File Name: calloc_test.c
> Author: conbiao
> Created Time: 2024年09月11日 星期三 16时31分19秒
************************************************************************/
#include <stdio.h><