我的C ++程序如下:
#include<iostream>
#include<conio.h>
using namespace std;
int a;
struct CARE{
long L1;
void init()
{
L1=100;
}
void intake()
{
a++;
L1+=++a;
}
void takeout()
{
int k=5;
cout<<a*k<<'#'<<L1-a;
}
};
int main()
{
CARE c[3];
for(int i=0;i<3;i++)
c[i].init();
for(int j=0;j<3;j++)
c[j].intake();
for(int m=0;m<3;m++)
c[m].takeout();
return 0;
getch();
}
Run Code Online (Sandbox Code Playgroud)
输出结果是:
30#9630#9830#100
根据我的说法,“ a”将是一个垃圾变量,并且每个输出都将彼此不同,但是这里不是这种情况。有人可以解释为什么吗?
这个问题纯粹出于好奇。我最近了解到,如果在Heap中动态分配内存空间,则删除内存空间非常重要。我的问题是,如果知道内存空间的地址,是否可以使用另一种C ++程序(从创建内存空间的程序)删除动态分配的内存空间?
这是一个例子:
代码01
#include <iostream>
using namespace std;
int main() {
int *a = new int;
cout << a;
int foo;
cin >> foo; // for blocking the program from closing.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
CODE01.CPP的输出(例如)
0x7c1640
CODE02.CPP
#include <iostream>
using namespace std;
int main() {
int *a = (int*)0x7c1640;
delete a;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这样行吗?如果我先运行code01.cpp,然后立即code02.cpp将堆中的内存删除了?