std::free

定义于头文件 <cstdlib>
void free( void* ptr );

解分配先前由 std::malloc()std::calloc() std::aligned_alloc (C++17 起)std::realloc() 分配的内存空间。

ptr 是空指针,则函数不做任何事。

ptr 的值不等于先前 std::malloc()std::calloc() std::aligned_alloc (C++17 起)std::realloc() 返回的值,则行为未定义。

ptr 所指代的内存区域已被解分配,即已以 ptr 为参数掉调用 std::free()std::realloc() ,且无对 std::malloc()std::calloc() std::aligned_alloc (C++17 起)std::realloc() 产生等于之前 ptr 的指针,则行为未定义。

若在 std::free() 返回后,通过指针 ptr 访问(除非另一分配函数恰好产生等于 ptr 的指针值),则行为未定义。

要求下列函数是线程安全的:

对这些分配或解分配特定存储单元的函数调用以单独全序出现,并且在此顺序中,每个解分配调用先发生于下个分配(若存在)。

(C++11 起)

目录

参数

ptr - 指向要解分配的内存的指针

返回值

(无)

注意

此函数接受空指针(不做任何事)以减少特殊情况的总数。无论分配是否成功,分配函数返回的指针都能传递给 free()

示例

#include <cstdlib>
 
int main()
{
    int* p1 = (int*)std::malloc(10*sizeof *p1);
    std::free(p1); // 每个分配的指针都必须释放
 
    int* p2 = (int*)std::calloc(10, sizeof *p2);
    int* p3 = (int*)std::realloc(p2, 1000*sizeof *p3);
    if(p3) // p3 非空表示 p2 为 std::realloc 所释放
       std::free(p3);
    else // p3 空表示 p2 未被释放
       std::free(p2);
}


参阅

freeC 文档

版本历史

  • (当前 | 先前 2017年8月29日 (二) 23:33Fruderica讨论 | 贡献. . (1,909字节) (+127). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 16:57P12bot讨论 | 贡献 . . (1,782字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 09:02P12bot讨论 | 贡献 . . (1,782字节) (-41). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 16:32P12bot讨论 | 贡献 . . (1,823字节) (+100). . (r2.7.3) (机器人添加:de, en, es, it, ru 去除:zh) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 03:25P12讨论 | 贡献 . . (1,723字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (1,723字节) (-48). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 14:09P12讨论 | 贡献 . . (1,771字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,771字节) (+913). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年5月4日 (五) 15:21P12bot讨论 | 贡献 . . (858字节) (+126). . (r2.7.3) (机器人添加:en, fr, ja, pl, pt) (撤销)
  • 当前 | 先前 2012年5月1日 (二) 03:37P12讨论 | 贡献 . . (732字节) (0). . (1个修订: Import from Dokuwiki) (撤销)
  • 当前 | 先前) 2012年5月1日 (二) 03:37P12讨论 | 贡献. . (732字节) (+732). . (Import from dokuwiki)