如何查看变量到底存储在了哪个区?
通过对进程内存分区的学习,了解到了进程的四大内存分区:代码区、全局区、堆区和栈区,那么程序中的某个变量,怎么判断或者查看它到底存储在了哪里?
参考
通过命令行进行查看,命令:ps -aux
其中
PID
为进程号,我们后续将根据进程号进行查看。
rw -p
为权限,表示读写。
搜索在堆的内存地址,通过打印变量的内存地址,与之对比,即可知道该变量位于堆上还是栈上。
以源程序stack_4.cpp为例
// 后缀表达式(逆波兰表达式)
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int caculate(string ¬ation)
{
// 1 创建一个栈对象oprands存储操作数
stack<int> oprands;
int result = 0;
// 2 从左往右遍历表达式,如果为操作数就入栈,如果是运算符,就从栈中弹出两个操作数进行计算,并将计算结果压入栈中
for (int i = 0; i < notation.length(); i++)
{
char current = notation[i];
cout<<notation[i]<<endl;
int o1, o2;
switch (current)
{
case '+':
o1 = oprands.top();
oprands.pop(); // pop不返回任何值,无法直接进行o1=oprands.pop()操作
o2 = oprands.top();
oprands.pop();
result = o2 + o1;
oprands.push(result);
break;
case '-':
o1 = oprands.top();
oprands.pop(); // pop不返回任何值,无法直接进行o1=oprands.pop()操作
o2 = oprands.top();
oprands.pop();
result = o2 - o1; //o1-o2的后缀表达式为o1 o2 -,出栈顺序为o2 o1,除法同理
oprands.push(result);
break;
case '*':
o1 = oprands.top();
oprands.pop(); // pop不返回任何值,无法直接进行o1=oprands.pop()操作
o2 = oprands.top();
oprands.pop();
result = o2 * o1;
oprands.push(result);
break;
case '/':
o1 = oprands.top();
oprands.pop(); // pop不返回任何值,无法直接进行o1=oprands.pop()操作
o2 = oprands.top();
oprands.pop();
result = o2 / o1;
oprands.push(result);
break;
default:
oprands.push(current);
break;
}
}
result = oprands.top();
return result;
}
int main()
{
string test = "352-*7+";
cout << "test = 352-*7+ = " << caculate(test) << endl;
getchar(); //!注意暂停,否则程序执行到return 0之后将结束进程
return 0;
}
编译执行:
注意不要回车,打开一个新的命令行终端: