栈区与堆区

栈区与堆区同为内存中的分区,其中栈区是一种先进后出的结构,由编译器自动分配释放;而堆区容量远大于栈,用于动态内存分配,可有程序员手动分配与释放。

二者在使用过程中有以下注意事项。

1.栈区注意事项:

首先我们做一个实验,写一个函数myFunc() 返回局部变量的地址 定义一个指针变量p接收

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

int* myFunc() {
	int a = 10;
	return &a;
}

void test01() {

	int* p = myFunc();
	printf("*p=%d\n", *p);
	printf("*p=%d\n", *p);
}
int main() { 

	test01();

	system("pause"); 
	return EXIT_SUCCESS; 
}

 实际上我们不能通过*p获得局部变量a的值,因为局部变量a分配在栈区,会随着函数调用结束而自动释放掉。至于为什么第一次打印可以正确获得a的值,是因为编译器为我们保留了一次,后面再用就不对了。

总结:不要返回局部变量的地址,局部变量在函数执行之后就被释放了,释放的内存就没有权限去操作,如果操作,结果未知!

2. 堆区注意事项

如果函数想要返回局部变量地址,我们可以把局部变量开辟在堆区,但要注意手动释放。

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

int* getSpace() {
	int * p = (int *)malloc(sizeof(int) * 5); // 堆区开辟4*5个字节 等同于int类型的数组int arr[5]
	if (p == NULL) {
		printf("分配内存失败");
		return;
	}
	for (int i = 0; i < 5; i++) {
		p[i] = i + 100;
	}
	return p;
}

void test01() {

	int* p = getSpace();
	for (int i = 0; i < 5; i++) {
		printf("%d\n", p[i]);
	}
	free(p); //释放堆区数据
	p = NULL; // 防止出现野指针
}

int main() { 

	test01();

	system("pause"); 
	return EXIT_SUCCESS; 
}

程序可以正确执行。

 给指针开辟内存:

给定一个开辟内存的函数allocateSpace(),定义一个空指针p,作为函数allocateSpace()的参数

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

void allocateSpace(char *pp) {
	char* tmp = malloc(100);//堆区分配100字节
	memset(tmp, 0, 100); // 内存置空
	strcpy(tmp, "hello world");
	pp = tmp;
}

void test02() {
	char* p = NULL;
	allocateSpace(p);
	printf("%s\n", p);
}

int main() { 

	test02();

	system("pause"); 
	return EXIT_SUCCESS; 
} 

 程序运行结果如上。实际上在allocateSpace()函数中,没有改变指针p所对应的内存空间。

注意事项:给指针进行内存开辟时,传入函数中不要用同级的指针,需要传入指针的地址,函数中接收这个地址后在进行内存开辟。

实验代码更改:

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

// 注意事项
// 参数为一个二级指针 接收一级指针的地址
void allocateSpace(char **pp) {
	char* tmp = malloc(100);//堆区分配100字节
	memset(tmp, 0, 100); // 内存置空
	strcpy(tmp, "hello world");
	*pp = tmp;
}

void test02() {
	char* p = NULL;
	allocateSpace(&p);
	printf("%s\n", p);
}

int main() { 

	test02();

	system("pause"); 
	return EXIT_SUCCESS; 
} 

 程序就可以正确执行了。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值