动态内存
——C/C++定义了4个内存区间:
·代码区/全局变量与静态变量区/局部变量区(栈区)/动态存储区(堆区)
——静态存储分配
·通常定义变量,编译器再编译都可以根据该变量知道所需内存的空间大小,系统在适当的时候为它分配确定的存储空间。
——在栈上创建。在执行函数时,函数内局部变量存储单元都可以在栈上创建,函数结束时自动释放。效率高,但是分配的内存容量有限。
在Linux@Ubuntu中:大小为8192KB
动态内存
·动态存储分配
——有些操作对象只有在程序运行时才能确定,系统根据运行时的要求进行内存分配。
——所有动态存储分配都在堆区进行。
——从堆上分配,也叫动态内存分配,malloc申请内存,free释放内存。
——堆区是不会自动在分配时做初始化,
·malloc/free
void * malloc(size_t num)
void free(void *p)
malloc(字节数) 返回值 : 申请成功返回内存地址,失败返回NULL
问题1:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
char * get_string()
{
char s[]="welcome";
return s;
}
int main()
{
char * p;
p = get_string();
printf("%s\n",p);
return 0;
}
代码结果:
字符串未能正确显示。
s 属于栈上,函数结束会自动释放,主函数指针p无法指向正确地址,所以显示乱码
修改如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
char * get_string()
{
//方式1
static char s[]="welcome";
//方式2
char * s = "welcome";
return s;
}
int main()
{
char * p;
p = get_string();
printf("%s\n",p);
return 0;
}
方式1:static char s[] 声明在堆,不会释放,所以 p 一直指向s
方式2:*s 存放在静态存储区,与全局变量、静态变量存储方式一致,不会自动释放
缺点:该变量会跟随程序直到结束,一直占内存
显示成功
综合实例程序:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#define N 20
typedef struct student{
int no;
char name[N];
float score;
}Stu;
Stu * get_info(){
Stu *p;
if((p = (Stu *)malloc(sizeof(Stu)))==NULL)
{
printf("malloc error\n");
return NULL;
}
p->no = 1;
strcpy(p->name,"Tom");
p->score = 90;
return p;
}
int main()
{
Stu *s;
if((s= get_info())==NULL)
{
return 0;
}
printf("Student info:%d %s %.2f\n",s->no,s->name,s->score);
free(s);
s=NULL;
return 0;
}
结果显示: