目录
C/C++程序的内存开辟
题目1
题目2
题目3
题目4
今天我们来接着讲几道经典的笔试题。首先来了解一下c\c++程序的内存开辟,使我们做题的头脑更加清晰。
C/C++程序内存分配的几个区域:
- 栈区(stack):在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时这些存储单元自动被释放。栈内存分配运算内置于处理器的指令集中,效率很高,但是分配的内存容量有限。 栈区主要存放运行函数而分配的局部变量、函数参数、返回数据、返回地址等。
- 堆区(heap):一般由程序员分配释放, 若程序员不释放,程序结束时可能由OS回收。分配方式类似于链表。
- 数据段(静态区)(static)存放全局变量、静态数据。程序结束后由系统释放。
- 代码段:存放函数体(类成员函数和全局函数)的二进制代码。
- 有了这幅图,我们就可以更好的理解在《C语言初识》中讲的static关键字修饰局部变量的例子了。实际上普通的局部变量是在栈区分配空间的,栈区的特点是在上面创建的变量出了作用域就销毁。但是被static修饰的变量存放在数据段(静态区),数据段的特点是在上面创建的变量,直到程序结束才销毁,所以生命周期变。
学习了【函数栈帧的创建与销毁】是更容易理解哦
下面题目我们讲从考点 题目代码本身 注意点 修改去解释。
请问运行下面题目的Test函数会有什么样的结果?
考点:
1.形参是实参的一份临时拷贝
2.内存泄漏
3.堆区的内存创建与销毁
#include
#include
#include
void GetMemory(char* p)
{
p = (char*)malloc(100);
}
void Test(void)
{
char* str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
int main()
{
Test();
return 0;
}
【修改方案一 】
#include
#include
#include
void GetMemory(char** p)//
{
*p = (char*)malloc(100);//
}
void Test(void)
{
char* str = NULL;
GetMemory(&str);
strcpy(str, "hello world");
printf(str);
free(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
【修改方案二】
#include
#include
#include
char* GetMemory(char* p)//这里也可以不传参
{
p = (char*)malloc(100);
return p;
}
void Test(void)
{
char* str = NULL;
str=GetMemory(str);//也可不传参数
strcpy(str, "hello world");
printf(str);
free(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
考点:返回栈空间地址
1.栈区的内存创建与销毁
2.野指针
#include
char* GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char* str = NULL;
str = GetMemory();
printf(str);
}
int main()
{
Test();
return 0;
}
✔当然,还存在一个问题,很多人很容易混淆,【栈空间地址 】和【栈空间变量】的问题。
考点:内存泄露
#include
#include
#include
void GetMemory(char** p, int num)
{
*p = (char*)malloc(num);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
int main()
{
Test();
return 0;
}
【修改方案】
#include
#include
#include
void GetMemory(char** p, int num)
{
*p = (char*)malloc(num);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
free(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
考点:非法访问,野指针
#include
#include
#include
void Test(void)
{
char* str = (char*)malloc(100);
strcpy(str, "hello");
free(str);
if (str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
int main()
{
Test();
return 0;
}
【修改方案】
#include
#include
#include
void Test(void)
{
char* str = (char*)malloc(100);
strcpy(str, "hello");
free(str);
str = NULL;
if (str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
int main()
{
Test();
return 0;
}
学习真的得重复做。我们加油敲代码哈。
✔✔✔✔✔最后,感谢大家的阅读,若有错误和不足,欢迎指正!下篇博文我们讲解【柔性数组】。
代码------→【gitee:唐棣棣 (TSQXG) - Gitee.com】
联系------→【邮箱:[email protected]】