堆栈

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

int global_uninit_var;
int global_init_var1 = 520;
int global_init_var2 = 880;

void func(void);

void func(void)
{
	;
}

int main(void)
{
	int local_var1;
	int local_var2;

	static int static_uninit_var;
	static int static_init_var = 456;

	char *str1 = "I love FishC.com!";
	char *str2 = "You are right!";

	int *malloc_var = (int *)malloc(sizeof(int));

	printf("addr of func -> %p\n", func);
	printf("addr of str1 -> %p\n", str1);
	printf("addr of str2 -> %p\n", str2);
	printf("addr of global_init_var1 -> %p\n", &global_init_var1);
	printf("addr of global_init_var2 -> %p\n", &global_init_var2);
	printf("addr of static_init_var -> %p\n", &static_init_var);
	printf("addr of static_uninit_var -> %p\n", &static_uninit_var);
	printf("addr of global_uninit_var -> %p\n", &global_uninit_var);
	printf("addr of malloc_var -> %p\n", malloc_var);
	printf("addr of local_var1 -> %p\n", &local_var1);
	printf("addr of local_var2 -> %p\n", &local_var2);

	return 0;
}

代码段:通常用来存放程序执行代码的内存区域

数据段通常用来存放已经初始化的全局变量和局部静态变量

bss段存放未初始化的全局变量的一块内存区域

堆和栈的区别:

堆由程序员手动申请 栈由系统自动分配

堆由程序员手动释放,栈由系统自动释放

#include <stdio.h>
#include<stdlib.h> 
int *func(){
	int *ptr=NULL;
	ptr=(int*)malloc(sizeof(int));
	if(ptr==NULL){
		exit(1);
	}
	*ptr=520;
	return ptr;
} 
int main(void)
{
int *ptr=NULL;
ptr=func();
printf("%d",*ptr);
free(ptr);

	return 0;
}

#include<iostream>
#include<stdlib.h>
using namespace std;
int main(){
	int *ptr1=NULL;
	int *ptr2=NULL;//栈局部变量 函数参数 函数返回值 
	ptr1=(int*) malloc(sizeof(int));//堆中 
	ptr2=(int*)malloc(sizeof(int));
	printf("栈%p   %p\n",&ptr1,&ptr2);
	printf("堆%p    %p",ptr1,ptr2); 
}
#include <stdio.h>

int main(void)
{
	char a = 0, b = 0;
	int *p = (int *)&b;

	*p = 258;

	printf("%d %d\n", a, b);

	return 0;
}

 

posted @ 2019-07-10 18:34  Hello_World2020  阅读(182)  评论(0编辑  收藏  举报