1.函式區域變數地址釋放的坑
main()呼叫test()方法,回傳a的地址,但是a是test()的區域變數,因此在test()呼叫結束之后,test()的堆疊空間就被移除,a的儲存空間被釋放,即使保存了指向a的指標,也無法獲得10. 第一次能得到10的原因是編譯器優化保留了一次資料,
#include <iostream>
using namespace std;
int* test();
int main(){
int *p = test();
cout<< *p <<endl;
cout<< *p <<endl;
//答案是10 0
}
int* test(){
int a = 10;
return &a;
}
2.字串和char*的表現
從這個實驗里,發現string的地址是沒有變化的,即使函式執行完畢,也能獲得正確的值,
解釋:字串是存在靜態區內的而非函式堆疊內,消亡的方式與普通變數不一樣,所以依舊可以正確獲取其值
? char*與上個例子的變數一樣,出來就沒了,
#include <iostream>
#include <string>
using namespace std;
string test();
char* test1();
int* test2();
int main() {
string p = test();
cout << "變數string的地址" << &p << endl;
cout << p << endl;
cout << p << endl;
char* p1 = test1();
printf("變數char陣列的地址%p\n", p1);
cout << "char陣列的值" << *p1 << endl;
cout << "char陣列的值" << *p1<< endl;
/**
結果是
變數string在函式里的地址0x6ffe00
變數string的地址0x6ffe00
helloworld
helloworld
變數char在函式中的地址00000000006ffdc0
變數char陣列的地址00000000006ffdc0
char陣列的值
char陣列的值
**/
}
string test() {
string a = "helloworld";
cout << "變數string在函式里的地址\n" << &a << endl;
return a;
}
char* test1() {
char a[] = { 'h','h','h' };
printf("char陣列在函式中的地址%p\n", a);
return a;
}
將以上區域變數存放在堆中則可以避免
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/230134.html
標籤:C++
上一篇:CPU實作原子操作的原理
下一篇:C++基礎知識篇:C++ 判斷
