目录
动态内存函数介绍
malloc函数
calloc函数
realloc函数
free函数
malloc函数
void *malloc( size_t size );
malloc函数用于申请一块连续可用的空间。
申请成功,则返回这块空间的起始地址。
申请失败,则返回空指针。
free函数
void free( void *memblock );
free函数用来释放动态开辟的内存。
free函数只能释放动态开辟的内存!释放完要把指针置空!否则会出现野指针。
若传入空指针,则free函数无意义。
int main()
{
int* tmp = (int*)malloc(sizeof(int) * 100);
if (tmp != NULL)
{
for (int i = 0; i < 100; i++)
{
*(tmp + i) = i;
printf("%d ", *(tmp + i));
}
}
free(tmp);
tmp = NULL;
return 0;
}
calloc函数
void *calloc( size_t num, size_t size );
calloc是为 num 个大小为 size 的元素开辟一块空间,并且把空间的每个字节初始化为0。
其与malloc函数区别就是多了初始化功能。
int main()
{
int* tmp = (int*)calloc(10,sizeof(int));
if (tmp != NULL)
{
for (int i = 0; i < 10; i++)
{
printf("%d ", *(tmp + i));
}
}
free(tmp);
tmp = NULL;
return 0;
}
realloc函数
void *realloc( void *memblock, size_t size );
realloc函数用于调整动态开辟的内存大小。
memblock 是要调整的内存地址 size 调整之后新大小 。
柔性数组
typedef struct st_type
{
int i;
int a[0];//柔性数组成员
}type_a;
typedef struct st_type
{
int i;
int a[];//柔性数组成员
}type_a;
结构体柔性数组成员前必有一个其他成员。
sizeof返回的结构体大小不包括柔性数组大小。
动态开辟内存应大于结构体内存,以适应柔性数组。
typedef struct st_type
{
int i;
int a[0];//柔性数组成员
}type_a;
int main()
{
printf("%d", (int)sizeof(type_a));//结果是4
}
柔性数组使用
typedef struct st_type
{
int i;
int a[0];//柔性数组成员
}type_a;
int main()
{
type_a* p = (type_a*)malloc(sizeof(type_a) + sizeof(int) * 100);
if (p == NULL)
{
return 1;
}
//相当于a[100],为数组a开辟了100个整型大小
free(p);
p = NULL;//方便内存释放,只需要释放一次
printf("%d", (int)sizeof(type_a));//结果是4
}
上述有柔性数组也可以这样设计
typedef struct st_type
{
int i;
int* pa;
}type_a;
int main()
{//开辟空间
type_a* p = (type_a*)malloc(sizeof(type_a));
if (p == NULL)
{
return 1;
}
p->pa = (int*)malloc(sizeof(int) * 100);
if (p->pa == NULL)
{
return 1;
}
//释放内存
free(p->pa);
p->pa = NULL;
free(p);
p = NULL;
}
通过上述对比,我们可以知道柔性数组的优点。
1.方便内存释放
2.有利于访问速度.(柔性数组内存开辟是连续的)
以上就是关于动态内存开辟的介绍。