通俗易懂C语言--内存管理

简单点说:内存管理四个区:代码区,静态区,堆区,栈区

#include <stdio.h>


static int g;

int sum(){
     int e=1,f=2,d;
	  d=e+f;
	 printf("d的地址:%d\n",&d);
	 return d;
}

void main(){
    int a,b,c;
	sum();
	printf("a的地址:%d\n",&a);
	printf("b的地址:%d\n",&b);
	printf("c的地址:%d\n",&c);
    printf("sum的地址:%d\n",&sum);
	printf("g的地址:%d\n",&g);
	printf("main的地址:%d\n",&main);
}
d的地址:1703620
a的地址:1703724
b的地址:1703720
c的地址:1703716
sum的地址:4198415
g的地址:4357684
main的地址:4198405

 一个程序看出来,所有可执行的代码都加载在代码区,包括函数(main函数也是),静态变量和全局变量放在静态区,局部变量以及形参是放在栈区,可以看到abc的地址依次从大到小,就跟一根很长的管子,底部是封闭的,管子的长度计数是从开口开始的,你放一颗弹珠下去,计数100厘米,你再放一颗下去,计数99厘米,依次这么放,但是当你取弹珠的时候,总不可能取100厘米的那一颗吧,这就是栈的先进后出。理解这也就很容易理解什么叫栈溢出了,就是我这栈空间已经满了,管子装不下了,还要硬往里面塞弹珠,这就是栈溢出了。

堆区

 着重讲一下堆区,因为这种在代码中经常用到,特别是有关结构体的,结构体就是存储数据的,但是当你要拿来用的时候,你不知道这个结构体存放了多少数据,而你又要拿来修改使用,那么就必须使用堆区,也就是我不知道这个数据多大,但是我给你开辟一个比较大的内存空间给你。

malloc

看一下声明:

void *malloc(size_t size)

 这就是一个指针函数是不是,size是内存块的大小,以字节为单位,既然是指针函数,那么该函数返回的就是一个指针 ,指向已分配大小的内存,如果请求失败,则返回 NULL。

free

同样看一下声明:

void free(void *ptr)

 用的话配对就行,你给谁分配了内存,再给它释放就行。

看下基础的:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{

char*a=NULL;
    
a=(char*)malloc(sizeof(char));

if(!a)
        
{
	printf("memory malloc fail\n");
}

printf("memory malloc success\n");
    
free(a);

return 0;
 
}

现在主要讨论的是怎么给结构体指针分配内存:

#include <stdio.h> 
#include <stdlib.h>  
 
struct student{ 
char name; 
int score; 
}; 

int main(){ 
 struct student  *stu1;

 stu1 = (struct student*)malloc(sizeof(struct student));
 
 if(!stu1){
   printf("malloc fail\n");
 }
stu1->score = 100; 
stu1->name = 'a';
printf("name %c, score %d \n ",stu1->name, stu1->score); 
free(stu1); 
return 0; 
}

结构体中常规的数据,貌似只要给这个结构体指针分配内存就行,输出结果:a,100,那如果不分配内存呢,我们应该怎么写?

#include <stdio.h> 
#include <stdlib.h> 
 
struct student{ 
char name; 
int score; 
};

struct student stu; 

int main(){ 
 struct student  *stu1;
  stu1=&stu;
// stu1 = (struct student*)malloc(sizeof(struct student));
 
// if(!stu1){
//   printf("malloc fail\n");
// }
stu1->score = 100; 
stu1->name = 'a';
printf("name %c, score %d \n ",stu1->name, stu1->score); 
//free(stu1); 
return 0; 
}

那就必须像上面那样写才能正确输出,具体的可以看结构体那一节

如果结构体成员有指针成员呢,那么给结构体指针分配内存后,还要给指针成员分配内存

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
 
struct student{ 
char *name; 
int score; 
};

int main(){ 
 struct student  *stu1;
 stu1 = (struct student*)malloc(sizeof(struct student));
 stu1->name = (char*)malloc(sizeof(char));
 strcpy(stu1->name,"anthony"); 
stu1->score = 100; 
printf("name %s, score %d \n ",stu1->name, stu1->score); 
free(stu1); 
return 0; 
}

但是结构体指针成员最后就不要释放了

总的来说大概就这些吧,其他的有空了再钻研钻研------------------------------------

おすすめ

転載: blog.csdn.net/u011397314/article/details/121420381