堆中聲明和棧中聲明:
#include <iostream>
class new_test{
public:
int a;
int b;
};
using namespace std;
void* stack_bottom=NULL;
void ptr_in_stack(new_test* ptr)
{
//函數調用時處於棧頂位置。
void* stack_top=&stack_top;//獲取棧頂位置
if( stack_bottom>ptr && stack_top<ptr)//比較地址範圍
{
cout<<"指針"<<ptr<<"在棧中"<<endl;
}
else
{
cout<<"指針"<<ptr<<"不在棧中"<<endl;
}
return ;
}
int main() {
int i;
stack_bottom=&i;//記錄下棧底的大概位置。
new_test a;//棧中聲明的abc
new_test b;
new_test c;
new_test *p1=new new_test;//堆中
new_test *p2=new new_test;
new_test *p3=new new_test;
cout<<"a address is: "<<&a<<endl;
cout<<"b address is: "<<&b<<endl;
cout<<"c address is: "<<&c<<endl;
cout<<"p1 address is: "<<p1<<endl;
ptr_in_stack(p1);
cout<<"p2 address is: "<<p2<<endl;
ptr_in_stack(p2);
cout<<"p3 address is: "<<p3<<endl;
ptr_in_stack(p3);
system("pause");
return 0;
}
運行結果如下所示:
從上圖可以看出,abc的內存地址是依次減小的,這也符合棧中地址從高位到地位的特性,使用new方法申請的三個結構體也證明不存在與棧中。
關於刪除:
棧中的結構體會自動刪除,但是堆中的需要手動用delete刪除,並且數組形式的也要加上[],但是如果結構體只包含基本的數據類型,好像使用delete p和使用delete []p效果是一樣的:
#include <iostream>
class new_test{
public:
int a;
int b;
};
using namespace std;
int main() {
new_test *p=new new_test[2];
new_test *p1=&p[0];
new_test *p2=&p[1];
p1->a=1;
p2->a=2;
cout<<"p1 is: "<<p1<<" p2 is: "<<p2<<endl;
cout<<"p1的a:"<<p1->a;
cout<<endl;
cout<<"p2的a:"<<p2->a<<endl;
delete p;
cout<<"p1 is: "<<p1<<" p2 is: "<<p2<<endl;
cout<<"p1的a:"<<p1->a;
cout<<endl;
cout<<"p2的a:"<<p2->a<<endl;
_CrtDumpMemoryLeaks();
system("pause");
return 0;
}
輸出結果:
可以看出p1和p2指向的好像都是被成功刪除了,並且檢測函數並沒有輸出檢測到內存泄漏,試試複雜的結構體,看這樣是否還是可以:
#include <iostream>
using namespace std;
class new_test
{
public:
int a;
new_test() { a=0; }
~new_test() { cout<<"~new_test()"<<endl; }
void test(int n) { a=n; }
};
int main() {
new_test *p=new new_test[2];
new_test *p1=&p[0];
new_test *p2=&p[1];
p1->a=1;
p2->a=2;
cout<<"p1 is: "<<p1<<" p2 is: "<<p2<<endl;
cout<<"p1的a:"<<p1->a;
cout<<endl;
cout<<"p2的a:"<<p2->a<<endl;
delete p;
cout<<"p1 is: "<<p1<<" p2 is: "<<p2<<endl;
cout<<"p1的a:"<<p1->a;
cout<<endl;
cout<<"p2的a:"<<p2->a<<endl;
_CrtDumpMemoryLeaks();
system("pause");
return 0;
}
輸出結果報錯,而且可以看到只析構了一個結構體:
改成了delete[] p,再看輸出結果應該是正確得了:
兩者爲啥不一樣還需要在做實驗判斷下。