#include <iostream>
using namespace std;
class test
{
public:
int a,b[100];
test() {
cout << "Constructor called" << " \n " ;
a=10;
}
};
int main()
{
test a1;
test *b2;
test *pointer = new test;
cout << a1.a << endl;
cout << pointer->a << " \n ";
cout << b2->a << " \n ";
return 0;
}
我想知道是否只有兩個對象是由上面的代碼創建'a1'對象和'指針'對象指針。我假設指針'b2'沒有獲得分配給它的內存。在這種情況下,最後的「cout < b2-> a」應該會產生分段錯誤。我正在訪問我沒有分配內存的位置。但我沒有得到分段錯誤。編譯器只是打印一個隨機值。對象指針的C++內存分配
我的問題是「是三個對象分配內存還是隻有兩個」? 爲什麼沒有分段錯誤?
只有兩個對象,當你測試* b2;這只是一個指針,並且只會分配內存,就像它會爲32位的普通指針所做的那樣。 – AlexDan