C语言堆区
堆的内存成员手动申请,手动释放
简单示例:
#include <stdio.h>
int *getSpace()
{
int i;
int *p = malloc(sizeof(int) * 5);//这里手动申请20字节大小内存,将首地址给p
if (NULL == p)
{
return NULL;
}
//只要是连续的内存空间,都能使用下标的方式访问内存
for (i = 0; i < 5; ++i)
{
p[i] = 100 + i;
}
return p;
}
void test01()
{
int *ret = getSpace(); //这里将函数的返回值地址拷贝给ret因为上面函数中局部变量在函数运行结束之后就释放掉了
int i ;
for (i = 0; i < 5; ++i)
{
printf("%d ",ret[i]);
}
//用完堆内存,一定要释放
free(ret);
ret = NULL;
}
int main()
{
test01();
return 0;
}
运行结果:
100 101 102 103 104
再来一个示例:
#include <stdio.h>
//2.定义变量的时候一定要初始化,很多的Bug产生都是由于没有初始化造成的。
void allocateSpace(char *p)
{
p = malloc(100);
memset(p,0,100);
strcpy(p, "hello world!");
}
void test02()
{
char *p = NULL;
allocateSpace(p);
printf("p = %s\n",p);
}
int main()
{
test02();
return 0;
}
运行结果:
p = (null)
分析:
首先栈区分配4字节大小给p,值为NULL,然后函数allocateSpace()的形参char *p也在栈区中,值为NULL,之后手动分配内存100大小空间在堆区,并范围地址给p。接着常量区的数据为hello world
并拷贝到堆中。
现在程序执行到test02的printf函数之后,allocateSpace()函数的局部变量已经被释放掉了
看图:
问题:
1.并没有让test02的指针指向堆空间
2.没有释放堆内存
终极示例:
#include <stdio.h>
void allocateSpace02(char **p)//这里用多级指针就是说明,参数指向的是一级指针
{
char *temp = malloc(100);
memset(temp, 0, 100);
strcpy(temp, "hello world!");
*p = temp;
}
void test03()
{
char *p = NULL;
allocateSpace02(&p);
printf("p = %s\n", p);
}
int main()
{
test03();
return 0;
}
运行结果:
p = hello world!
分析:
首先栈区分配4字节大小给p,值为NULL,然后函数allocateSpace02()的形参char **p也在栈区中,值为NULL,temp在栈区中存放的是手动分配空间在堆区的地址0x0003,再将这个0x0003值赋值给※p从而test03中的p指向0x0003的地址,得到值为hello world
看图: