名稱空間
變體
操作

std::free

來自 cppreference.com
< cpp‎ | memory‎ | c
 
 
記憶體管理庫
(僅作說明*)
未初始化記憶體演算法
(C++17)
(C++17)
(C++17)
受約束的未初始化
記憶體演算法
C 庫
free


分配器
記憶體資源
垃圾回收支援
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化儲存
(直到 C++20*)
(直到 C++20*)
顯式生命週期管理
 
定義於標頭檔案 <cstdlib>
void free( void* ptr );

釋放先前由 std::mallocstd::callocstd::aligned_alloc(C++17 起)std::realloc 分配的空間。

如果 ptr 是空指標,則函式不執行任何操作。

如果 ptr 的值不等於先前由 std::mallocstd::callocstd::aligned_alloc(C++17 起)std::realloc 返回的值,則行為未定義。

如果 ptr 所引用的記憶體區域已被解除分配,即 std::freestd::realloc 已將 ptr 作為引數呼叫,並且之後沒有呼叫 std::mallocstd::callocstd::aligned_alloc(C++17 起)std::realloc 導致與 ptr 相等的指標,則行為未定義。

如果 std::free 返回後,透過指標 ptr 進行訪問(除非其他分配函式恰好導致指標值等於 ptr),則行為未定義。

以下函式必須是執行緒安全的

這些分配或解除分配特定儲存單元的函式呼叫以單一全序發生,且每個此類解除分配呼叫都 happens-before 此順序中的下一個分配(如果有)。

(C++11 起)

目錄

[編輯] 引數

ptr - 指向要解除分配的記憶體的指標

[編輯] 返回值

(無)

[編輯] 注意

函式接受(並且對)空指標不執行任何操作,以減少特殊情況處理。無論分配是否成功,分配函式返回的指標都可以傳遞給 std::free

[編輯] 示例

#include <cstdlib>
 
int main()
{
    int* p1 = (int*)std::malloc(10 * sizeof *p1);
    std::free(p1); // every allocated pointer must be freed
 
    int* p2 = (int*)std::calloc(10, sizeof *p2);
    int* p3 = (int*)std::realloc(p2, 1000 * sizeof *p3);
    if (!p3) // p3 null means realloc failed and p2 must be freed.
        std::free(p2);
    std::free(p3); // p3 can be freed whether or not it is null.
}

[編輯] 參閱

C documentation 關於 free 的文件