問題: 動態記憶體申請一定成功嗎?
c **:void code()
free(p);
}
c++ **:
void code()
delete p;
}
問題: new 語句中的異常是怎麼丟擲來的呢?
失敗
可以自定義 new_handler() 函式
void my_new_handler()
int main(int argc, char* ar**)
公用實驗**:
#include #include #include #include using namespace std;
class test
~test()
void* operator new (unsigned int size)
void operator delete(void* p)
void* operator new (unsigned int size)
void operator delete(void* p)
};
實驗 1:不同編譯器中 new_handler() 行為
void my_new_handler()
void ex_func_1()
}catch(const bad_alloc&)
}int main()
輸出:[g++]
func = 0
輸出:[vc++2010]
func = 00000000
輸出:[bcc]
func = 0x00401474
catch(catch bad_alloc&)
結論:預設情況下,g++,vc++2010 並沒有提供全域性的 new_handler() 函式;
gcc 提供了全域性的 new_handler() 函式,並丟擲了 bad_alloc 異常。
實驗 2:不同編譯器 new 失敗行為
void ex_func_2()
int main()
輸出:[g++]
test()
段錯誤輸出:[vc++2010]
operator new: 4
pt = 00000000
operator new: 24
pt = 00000000
輸出:[bcc]
operator new: 4
pt = 00000000
operator new: 24
pt = 00000000
分析:g++ 編譯生成的可執行檔案執行時發生段錯誤:
new 過載函式返回 null, 於是就在 0 位址處建立物件,呼叫建構函式。建構函式中,m_value = 0,導致段錯誤。
vc++2010:
如果 new 的過載返回 null,物件未建立,建構函式不會被呼叫
bcc:
如果 new 的過載返回 null,物件未建立,建構函式不會被呼叫
問題:如何跨編譯器統一 new 的行為, 提高**的移植性呢?
實驗 1: 類層次範圍類層次範圍
單此動態記憶體分配
#include #include #include #include using namespace std;
class test
~test()
void* operator new (unsigned int size) throw() // 注意這裡!
void operator delete(void* p)
void* operator new (unsigned int size) throw() // 注意這裡!
void operator delete(void* p)
};void ex_func_2()
int main()
輸出:[g++]
operator new: 4
pt = 0
operator new: 24
pt = 0
輸出:[vc++2010]
operator new: 4
pt = 00000000
operator new: 24
pt = 00000000
輸出:[bcc]
operator new: 4
pt = 00000000
operator new: 24
pt = 00000000
實驗 2:單次動態記憶體分配範圍
#include #include #include #include using namespace std;
void ex_func_3()
int main()
輸出:
p = 0x8300008
關於 new 的小知識點補充:
在指定的記憶體空間上建立物件(需要手動呼叫析構函式)
#include using namespace std;
int main()
; struct st
;st* pt = new(bb) st(); // 注意這裡!
pt->x = 1;
pt->y = 2;
cout << bb[0] << endl;
cout << bb[1] << endl;
pt->~st(); // 手動呼叫析構函式
return 0;
}
輸出:
12
動態記憶體申請的結果 專題2
實驗一 證明new handler全域性函式是否存在 include include include include using namespace std class test test void operator new unsigned int size void operator delet...
C語言動態記憶體申請分析
1 c語言中的一切操作都是基於記憶體的 2 變數和陣列都是記憶體的別名 1 記憶體分配由編譯器在編譯期間決定 2 定義陣列的時候必須指定陣列的長度 3 陣列的長度是在編譯期間就必須確定的 1 malloc和free用於執行動態記憶體分配和釋放 2 malloc所分配的是一塊連續的記憶體 3 mall...
關於動態記憶體申請的部落格
動態記憶體 malloc 動態申請記憶體 int arr int malloc n sizeof int int arr n 定義乙個n長度的陣列 如果要使用,需引用標頭檔案 需注意 1.棧的大小1m,可配 2.堆的分配的最大連續塊1.2g calloc動態申請記憶體,並將裡面的值置為0 int a...